aim aim - 6 months ago 71
Java Question

Property placeholder from Configuration

With Spring in xml context we can simple load properties like this:

<context:property-placeholder location:"classpath*:app.properties"/>


Is there any chance to configure same properties inside @Configuration bean (~ from java code) without boilerplate?

Thanks!

Answer Source

You can use the annotation @PropertySource like this

@Configuration
@PropertySource(value="classpath*:app.properties")
public class AppConfig {
 @Autowired
 Environment env;

 @Bean
 public TestBean testBean() {
     TestBean testBean = new TestBean();
     testBean.setName(env.getProperty("testbean.name"));
     return testBean;
 }
}

See: http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/context/annotation/PropertySource.html

EDIT: if you are using spring boot you can use @ConfigurationProperties annotation to wire the properties file directly to bean properties, see: https://www.mkyong.com/spring-boot/spring-boot-configurationproperties-example/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download