[英]What is the advantage of using Spring PropertySource?
在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
增加了Spring耦合 从属性文件中读取值远远优于在类文件中对它们进行硬编码。 如果您需要硬编码,那么如果要更改其中任何一个,则需要重新编译。
回答你的批评:
1。
系统属性是可迭代的,而PropertySource则不是
大多数PropertySources扩展EnumerablePropertySource。 虽然我不确定你想要迭代你的属性的用例
2。
PropertySource不允许回退属性 - 并且创建自定义PropertySource至少等于对系统属性执行相同操作的代码。
您可以使用标准的spring属性getter,而不是隐藏自定义属性源中的后退。 例如
env.getProperty("someProp", "someFallback")
甚至
env.getProperty("someProp", env.getProperty("someFallback", "lastResort"))
3。
环境和@Autowire增加了Spring耦合
它是自动接线,提供弹簧联轴器,如果你不想,你不需要使用它。 例如
public class Foo {
private final String foo;
public Foo(String foo) {
this.foo = foo;
}
public void bar() {
// doo something with foo
}
}
和
@Configuration
@PropertySource("classpath:foo.properties")
public class Config {
@Autowired
public Environment env;
@Bean
public Foo foo() {
return new Foo(env.getProperty("foo"));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.