【问题标题】:What is the advantage of using Spring PropertySource?使用 Spring PropertySource 有什么好处?
【发布时间】: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


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

    【讨论】:

      【解决方案2】:

      从属性文件中读取值比在类文件中硬编码要好得多。如果你硬编码,那么如果你想改变它们,你需要重新编译。

      回答您的批评:

      1.

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

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

      2.

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

      您可以使用标准的 spring 属性获取器,而不是在自定义属性源中隐藏回退。例如

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

      甚至

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

      3.

      Environment 和@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"));
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-06
        • 2012-11-28
        • 2010-09-21
        • 2011-04-28
        • 1970-01-01
        • 2011-09-16
        • 2011-04-24
        • 1970-01-01
        相关资源
        最近更新 更多