【发布时间】:2013-10-31 17:59:25
【问题描述】:
在 Spring 中使用@PropertySource 有什么好处?
给定一个配置...
@Configuration
@PropertySource("classpath:foo.properties")
public class Config {}
...我们可以访问Environment
public class Foo {
@Autowire Environment env;
public void bar() {
String foo = env.getProperty("foo");
}
}
我们已经可以使用常规系统属性来做到这一点。使用系统属性,即使是配置文件管理也很容易
if (profile1) System.setProperty("foo", "bar")
else System.setProperty("foo", "baz");
...和
System.getProperty("foo"); // also shorter than autowiring an environment
加上系统属性没有@PropertySource的一些缺点
- 系统属性是可迭代的,
PropertySource不是 -
PropertySource不允许回退属性 - 创建自定义PropertySource至少等于对系统属性执行相同操作的代码。 -
Environment和@Autowire增加弹簧耦合
【问题讨论】:
标签: java spring autowired system-properties