@PropertySource在Spring中使用有什么好处?
给定一个配置...
@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 耦合