How to inject complete propertiesfile in a springbean

Jan picture Jan · May 9, 2011 · Viewed 23.5k times · Source

I have a properties-file with a lot of values and I do not want to list them in my bean-configuration-file separately. E.g.:

<property name="foo">
    <value>${foo}</value>
</property>
<property name="bar">
    <value>${bar}</value>
</property>

and so on.

I imagine to inject all completely as java.util.Properties or less as a java.util.Map. Is there a way to do so?

Answer

rustyx picture rustyx · Jul 2, 2015

For Java config you can use something like this:

@Autowired @Qualifier("myProperties")
private Properties myProps;

@Bean(name="myProperties")
public Properties getMyProperties() throws IOException {
    return PropertiesLoaderUtils.loadProperties(
        new ClassPathResource("/myProperties.properties"));
}

You can also have multiple properties this way, if you assign a unique bean name (Qualifier) to each instance.