dimanche 1 mars 2015

Reading system properties with SPeL in Spring Framework

I need to get the following system property within one of my configuration files: -Dspring.profiles.active="development". Now I have seen countless of people suggest that this can be done with Spring Expression Language, but I cannot get it to work. Here is what I have tried (plus many variations hereof).



@Configuration
@ComponentScan(basePackages = { ... })
public class AppConfig {
@Autowired
private Environment environment;

@Value("${spring.profiles.active}")
private String activeProfileOne;

@Value("#{systemProperties['spring.profiles.active']}")
private String activeProfileTwo;

@Bean
public PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
Resource[] resources = {
new ClassPathResource("application.properties"),
new ClassPathResource("database.properties")

// ...
};

PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
propertySourcesPlaceholderConfigurer.setLocations(resources);
propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);

return propertySourcesPlaceholderConfigurer;
}
}


All of the properties are NULL. The same happens if I try to access any other system property. I can access them without problems by invoking System.getProperty("spring.profiles.active"), but this is not as nice.


Many examples that I found configure the PropertySourcesPlaceholderConfigurer to also search system properties, so maybe this is why it does not work. However, those examples are in Spring 3 and XML configuration, setting a property that no longer exists on the class. Perhaps I have to call the setPropertySources method, but I am not entirely sure how to configure this.


Either way, I found multiple examples that suggest that my approach should work. Believe me, I searched around a lot. What's wrong?


Aucun commentaire:

Enregistrer un commentaire