Search code examples
springspring-java-config

Spring FactoryBean as reference for PropertySourcesPlaceholderConfigurer


Creating a FactoryBeany for loading the properties from the Zookeeper.

public class ZkPropertiesFactoryBean extends AbstractFactoryBean<Properties> {..}

While using XML config it is possible to refer the bean as follows

<bean id="zkProperties" class="test.ZkPropertiesFactoryBean"/>
<context:property-placeholder properties-ref="zkProperties"/>

I'm trying to convert XML config to Java config, using PropertySourcesPlaceholderConfigurer

    @Bean
    public  static PropertySourcesPlaceholderConfigurer loadProperties() throws Exception {
        PropertySourcesPlaceholderConfigurer prop = new PropertySourcesPlaceholderConfigurer();
        prop.setIgnoreUnresolvablePlaceholders(true);
        return prop;
    }

What is the equivalent of properties-ref? I'm not able to find any reference for doing the same.


Solution

  • You can use the setProperties of the PropertySourcesPlaceholderConfigurer and set it by using your AbstractFactoryBean.getObject() method:

    Your configuration could look something like:

       @Configuration
       public class ZookeeperConfig {
    
            @Autowired
            private ZkPropertiesFactoryBean zkPropertiesFactoryBean;
    
            @Bean
            public  static PropertySourcesPlaceholderConfigurer loadProperties() throws Exception {
                PropertySourcesPlaceholderConfigurer prop = new PropertySourcesPlaceholderConfigurer();
                prop.setIgnoreUnresolvablePlaceholders(true);
                prop.setProperties(zkPropertiesFactoryBean.getObject());
                return prop;
            }
        }