@PropertySources - 如何正确使用不同的来源?

时间:2015-06-02 14:13:46

标签: java spring

让我们考虑一下,我们有两个属性文件,并希望阅读其中一些属性。从 Spring 4.0 开始,可以使用注释 @PropertySources 来完成。我发现可以这样做:

@PropertySources({
    @PropertySource(name = "first", value = "classpath:first.properties"),
    @PropertySource(name = "second", value = "classpath:second.properties")
})
public class AppConfig {

    @Autowired
    Environment environment;

    @Bean
    public SomeBean someBean {
        //reading from first properties file
        org.springframework.core.env.PropertySource<?> first =
           ((StandardEnvironment) environment).getPropertySources().get("first"));    
        first.getProperty("someProperty");
        //reading from second properties file
        org.springframework.core.env.PropertySource<?> second =
           ((StandardEnvironment) environment).getPropertySources().get("second"));
        second.getProperty("someProperty");
    }
}

这是一种正确的方法吗?你知道一个更好的吗?

1 个答案:

答案 0 :(得分:0)

这可以做得更多:

@PropertySources({
    @PropertySource(name = AppConfig.FIRST, value = "classpath:first.properties"),
    @PropertySource(name = AppConfig.SECOND, value = "classpath:second.properties")
})    
public class AppConfig {

static final String FIRST = "first";
static final String SECOND = "second";

@Autowired
private AbstractEnvironment defaultConfiguration;

@Bean
public SomeBean someBean {
    //reading from first properties file         
    firstConfiguration().getProperty("someProperty");
    //reading from second properties file
    secondConfiguration().getProperty("someProperty");
}

@Bean
public org.springframework.core.env.PropertySource<?> firstConfiguraiton() {
    return defaultConfiguration.getPropertySources().get(FIRST);
}

@Bean
public org.springframework.core.env.PropertySource<?> secondConfiguration() {
    return defaultConfiguration.getPropertySources().get(SECOND);
}
}