【问题标题】:@PropertySources - how to use different sources properly?@PropertySources - 如何正确使用不同的来源?
【发布时间】:2015-06-04 14:27:34
【问题描述】:

假设我们有两个 properties 文件并且想要读取其中的一些属性。从 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");
    }
}

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

【问题讨论】:

  • 你获得房产的方式似乎很好。您可以通过使用属性源名称的常量来改进它。而不是强制转换,您可以自动装配 AbstractEnvironment 或类似的东西。如果您愿意,也可以使用 .getPropertySources().iterator()。
  • 好点,谢谢!

标签: java spring


【解决方案1】:

这是可以做的更多:

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

【讨论】:

    猜你喜欢
    • 2015-11-21
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多