【发布时间】: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()。
-
好点,谢谢!