使用Spring PropertySource有什么好处?

时间:2013-10-31 17:59:26

标签: java spring autowired system-properties

在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

Plus系统属性没有@PropertySource

的一些缺点
  • 系统属性是可迭代的,PropertySource不是
  • PropertySource不允许回退属性 - 并且创建自定义PropertySource至少等于使用系统属性执行相同操作的代码。
  • Environment@Autowire增加了Spring耦合

2 个答案:

答案 0 :(得分:3)

  1. 您可以为提供属性文件提供键/值对,并将其注入您的环境。如果您拥有大量环境属性,这将使其更容易一些。您也可以指定多个文件。
  2. 假设您事先知道该物业(在使用之前)。因此,关键值对是有意义的。
  3. 您有春季活动配置文件概念来管理配置文件。这比通过自己的系统属性更容易。

答案 1 :(得分:1)

从属性文件中读取值远远优于在类文件中对它们进行硬编码。如果您需要硬编码,那么如果您想更改其中任何一个,则需要重新编译。

回答你的批评:

1

  

系统属性是可迭代的,PropertySource不是

大多数PropertySources扩展EnumerablePropertySource。虽然我不确定你想要迭代你的属性的用例

2

  

PropertySource不允许回退属性 - 并创建一个   自定义PropertySource至少等于执行相同的代码   系统属性。

您可以使用标准的spring属性getter,而不是隐藏自定义属性源中的后备。 e.g。

env.getProperty("someProp", "someFallback")

甚至

env.getProperty("someProp", env.getProperty("someFallback", "lastResort"))

3

  

环境和@Autowire增加Spring耦合

这是自动接线,提供弹簧联轴器,如果你不想,你不需要使用它。 e.g。

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"));
    }
}
相关问题