Search code examples
javaspringspring-bootproperties-file

How can I get the bean of a property file in Spring-Boot?


I need to play around keys of a property file. Key will be dynamic, so I need the bean of property file as mentioned below as my current running Spring application.

Spring Configuration:

<bean id="multipleWriterLocations" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <value>classpath:writerLocations.properties</value>
                <value>file:config/writerLocations.properties</value>
            </list>
        </property>
    </bean>

Java Code:

Properties prop = appContext.getBean("multipleWriterLocations")

I need the same Properties bean instance in Spring-boot. I need to transform existing Spring application into Spring-Boot without changing the functionalities.

One way to get properties file value using @PropertySource(), but in this case I need the key name. But in my case, key name is not known and I need to fetch keySet from the Properties bean.


Solution

  • You can use @ImportResource("classpath:config.xml") where config.xml contains your PropertiesFactoryBean above, and then autowire it into your @SpringBootApplication or @Configuration class.

    @SpringBootApplication
    @ImportResource("classpath:config.xml")
    public class App {
        public App(PropertiesFactoryBean multipleWriterLocations) throws IOException {
            // Access the Properties populated from writerLocations.properties
            Properties properties = multipleWriterLocations.getObject();
            System.out.println(properties);
        }
    
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    }