8

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!

aim
  • 1,461
  • 1
  • 13
  • 26

3 Answers3

11

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, like this:

test.properties

name=John Doe
age=12

PersonProperties.java

@Component
@PropertySource("classpath:test.properties")
@ConfigurationProperties
public class GlobalProperties {

    private int age;
    private String name;

    //getters and setters
}

source: https://www.mkyong.com/spring-boot/spring-boot-configurationproperties-example/

rvazquezglez
  • 2,284
  • 28
  • 40
7

Manual configuration can be done via following code

public static PropertySourcesPlaceholderConfigurer loadProperties(){
  PropertySourcesPlaceholderConfigurer propertySPC =
   new PropertySourcesPlaceholderConfigurer();
  Resource[] resources = new ClassPathResource[ ]
   { new ClassPathResource( "yourfilename.properties" ) };
  propertySPC .setLocations( resources );
  propertySPC .setIgnoreUnresolvablePlaceholders( true );
  return propertySPC ;
}

Sources: Property Placeholder

Dangling Piyush
  • 3,658
  • 8
  • 37
  • 52
0

One easy solution is that your bean will also contain some init function:

In your spring configuration, you may mention it:

<bean id="TestBean" class="path to your class" init-method="init" singleton="false" lazy-init="true" >

init will be called after all properties will be set via setters, in this method you may override properties that have been already set, you may also set any properties.

Michael
  • 2,827
  • 4
  • 30
  • 47
  • @aim, Dangling Piyush, have provided you additional answer that shows you how to do it without xml – Michael Feb 06 '13 at 08:46