Spring JavaConfig for java.util.Properties field Spring JavaConfig for java.util.Properties field spring spring

Spring JavaConfig for java.util.Properties field


The XML base Way:

in spring config:

<util:properties id="myProperties" location="classpath:com/foo/my-production.properties"/>

in your class:

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

JavaConfig Only

It looks like there is an annotation:

@PropertySource("classpath:com/foo/my-production.properties")

Annotating a class with this will load the properties from the file in to the Environment. You then have to autowire the Environment into the class to get the properties.

@Configuration@PropertySource("classpath:com/foo/my-production.properties")public class AppConfig {@Autowiredprivate Environment env;public void someMethod() {    String prop = env.getProperty("my.prop.name");    ...}

I do not see a way to directly inject them into the Java.util.properties. But you could create a class that uses this annotation that acts as a wrapper, and builds the properties that way.


declare a PropertiesFactoryBean.

@Beanpublic PropertiesFactoryBean mailProperties() {    PropertiesFactoryBean bean = new PropertiesFactoryBean();    bean.setLocation(new ClassPathResource("mail.properties"));    return bean;}

Legacy code had following config

<bean id="mailConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  <property name="location" value="classpath:mail.properties"/></bean>

Converting that to Java config is super easy as shown above.


It is an old subject but there are also a more basic solution.

@Configurationpublic class MyConfig {    @Bean    public Properties myPropertyBean() {        Properties properties = new Properties();        properties.load(...);        return properties;    }}