Loading external spring properties in annotation based Spring 3.1 application


"As opposed to using XML namespace element, the Java @PropertySource annotation does not automatically register a PropertySourcesPlaceholderConfigurer with Spring. Instead, the bean must be explicitly defined in the configuration to get the property resolution mechanism working."
http://www.javaworld.com/community/?q=node/8309


Loading in AppConfig


@Configuration
@ComponentScan({ "package1","package2" ...})
@ImportResource("classpath:/someOtherImports.xml")
public class AppConfig {
    
    static Logger log = LoggerFactory.getLogger(AppConfig.class);

    /**
     * Load spring properties
     */
    @Bean
    public PropertySourcesPlaceholderConfigurer properties(){
      String propertiesLocation = System.getProperty("config.dir") + "/spring.properties";
      PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
      Resource[] resources = new FileSystemResource []{new FileSystemResource (propertiesLocation)};
      pspc.setLocations(resources);
      pspc.setIgnoreUnresolvablePlaceholders(true);
      log.info("Loading spring properties from " + propertiesLocation);
      return pspc;
    }
}


Using properties in Beans
As usual:
private @Value("${myprop}") String myprop; 







Comments