在Spring Framework中使用SPeL读取系统属性

时间:2015-03-01 17:29:15

标签: java spring spring-mvc spring-el

我需要在我的一个配置文件中获取以下系统属性:-Dspring.profiles.active="development"。现在我看到无数人都认为这可以通过Spring Expression Language完成,但我无法让它工作。这是我尝试过的(加上其中的许多变化)。

@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;
    }
}

所有属性都是NULL。如果我尝试访问任何其他系统属性,也会发生同样的情况。我可以通过调用System.getProperty("spring.profiles.active")来解决这些问题,但这并不是很好。

我发现的许多示例都将PropertySourcesPlaceholderConfigurer配置为搜索系统属性,因此可能这就是它无效的原因。但是,这些示例在Spring 3和XML配置中,设置了类中不再存在的属性。也许我必须调用setPropertySources方法,但我不完全确定如何配置它。

无论哪种方式,我发现了多个示例,表明我的方法应该有效。相信我,我搜索了很多。怎么了?

1 个答案:

答案 0 :(得分:3)

只需自动装配Spring Environment interface的实例,就像您实际执行的那样,然后询问活动环境是什么:

@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
    }
}