ba0708
ba0708

Reputation: 10599

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")

            // I want to use the active profile in the above file names
        };

        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?

Upvotes: 5

Views: 4585

Answers (1)

fps
fps

Reputation: 34450

Just autowire an instance of Spring's Environment interface, as you're actually doing and then ask what the active environment is:

@Configuration
public class AppConfig {

    @Autowired
    private Environment environment;

    @Bean
    public PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {

        List<String> envs = Arrays.asList(this.environment.getActiveProfiles());
        if (envs.contains("DEV")) {
            // return dev properties
        } else if (envs.contains("PROD")) {
            // return prod properties
        }
        // return default properties
    }
}

Upvotes: 4

Related Questions