[Spring] multiple PropertyPlaceholderConfigurer caused the placeholder not to be replaced

this is a Spring project,
the first PropertyPlaceholderConfigurer, in context-aaa.xml is mainly to configure JDBC properties

  https://jira.spring.io/browse.

I found the solution:
The alternative is to

(a) use the new PropertySourcesPlaceholderConfigurer instead of the traditional PropertyPlaceholderConfigurer;

(b) eliminate the first PropertySourcesPlaceholderConfigurer;

(c) register a PropertySource with the ApplicationContext"s Environment that contains the properties for the placeholders that need replacement in the PropertySourcesPlaceholderConfigurer

I would like to ask how to operate the third step?

Mar.05,2021

check to see if the order attribute is sorted with PropertyPlaceholderConfigurer, and why the xml file does not take effect when ignoreUnresolvablePlaceholders is true.


if I understand it correctly, your execution logic is:

DruidDataSource  -> jdbc.properties
beans  -> DruidDataSource

so what you need to do is after spring creates beans

DruidDataSource

beansPropertyPlaceholder

the following ways can be used for reference (the code needs to be modified according to your situation):

package com.bixuebihui;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;


public class BeanPostPrcessorImpl implements BeanPostProcessor {
    private Properties properties="jdbc.properties";
    
    // Bean 
    public Object postProcessBeforeInitialization(Object bean, String beanName)
           throws BeansException {
       //System.out.println("" + beanName + "");
        if(beanName.equals("druidDataSource")){
            try {
                //set druidDataSource's properties use properties
                ((DruidDataSource)bean).setUrl(properties.getProperty("url"));
                ......
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
       return bean;
    }

    // Bean 
    public Object postProcessAfterInitialization(Object bean, String beanName)
           throws BeansException {
       //System.out.println("" + beanName + "");
        //<bean class="com.spring.test.di.BeanPostPrcessorImpl"/>
       return bean;
    }
    
    public String getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }
}
    <bean id="properties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
        <value>classpath:jdbc.properties</value>
        </list>
    </property>
    </bean>

    <bean class="com.bixuebihui.BeanPostPrcessorImpl">
        <property name="properties" value="properties" />
    </bean>

reference:
https://codeshelper.com/a/11.

Menu