27

What would be the equivalent in java based configuration of XML based spring configuration

<util:properties id="mapper"  location="classpath:mapper.properties" />

To then be able to use this specific property object in code like :

@Resource(name = "mapper")
private Properties myTranslator;

Looking at the doc, I looked at the

@PropertySource

annotation but it seems to me that the particular propertyfile will not be able to be accessed individually from the Environment object.

Yves Nicolas
  • 6,901
  • 7
  • 25
  • 40

2 Answers2

36

Very simply, declare a PropertiesFactoryBean.

@Bean(name = "mapper")
public PropertiesFactoryBean mapper() {
    PropertiesFactoryBean bean = new PropertiesFactoryBean();
    bean.setLocation(new ClassPathResource("com/foo/jdbc-production.properties"));
    return bean;
}

In the documentation here, you'll notice that before they made <util:properties>, they used to use a PropertiesFactoryBean as such

<!-- creates a java.util.Properties instance with values loaded from the supplied location -->
<bean id="jdbcConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="location" value="classpath:com/foo/jdbc-production.properties"/>
</bean>

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

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 1
    Thanks. It looks like I have still some RTFM progresses to do;-) – Yves Nicolas Sep 19 '13 at 14:16
  • 4
    @YvesNicole You're welcome. I don't blame you, TFM is extremely long. – Sotirios Delimanolis Sep 19 '13 at 14:16
  • If you have web application and want to be able to read from `WEB-INF`, use `ServletContextResource`. If you want universal solution, use `ServletContextResourcePatternResolver`. Notice what you will need `ServletContext` reference in this case – Kirill Nov 10 '16 at 12:04
0

In Spring Boot 5+, application.properties under src/main/resources is the Convention. I have found if you need to put your own custom properties, for example "student.class.name", then Spring will automatically validate it in Eclipse and tag the entry with a warning, with the option to create metadata for it. Click it and it will create a JSON file under META-INF. Use that. Then you can inject the property using @Value("${student.class.name}" annotation.

Nick K
  • 1