【问题标题】:What configuration enables the evaluation of @Value annotations?什么配置可以评估 @Value 注释?
【发布时间】:2015-08-10 08:06:00
【问题描述】:

我想做一个非常简单的基于编程/注释的 Spring 配置,做一些命令行的东西,我希望能够从系统属性中注入一些 bean 值的值。

我正在像这样使用@Value:

@Value("${MigrateDb.task:default}")
private String task;

它有点工作,但它没有评估值定义,我只是在实际字段中得到“${MigrateDb.task:default}”,而不是 Spring 评估它并给我迁移的值。 db.task 系统属性(或默认)。

我需要在我的配置类中添加什么来启用此行为?

【问题讨论】:

    标签: spring


    【解决方案1】:

    尝试以这种方式使用它:

    @Value("${MigrateDb.task:default}")
    private String task;
    

    XML 配置:

    <context:property-placeholder
            location="your.filelocation.properties" />`
    

    Java 配置:

    @Bean
    public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
    
        PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
        propertyPlaceholderConfigurer.setLocation(new ClassPathResource("file.properties"));
    
        return propertyPlaceholderConfigurer;
    }
    

    【讨论】:

    • 为什么要使用SpEL,你不需要它,你的PropertyPlaceholderConfiguer应该是static,最好是PropertySourcesPlaceholderConfigurer
    【解决方案2】:

    从 ShadowRay 的回答来看,启用请求行为的最少代码是:

      @Bean
      public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer(){
          return new PropertyPlaceholderConfigurer();
      }
    

    方法应该是静态的:https://stackoverflow.com/a/14943106/924597

    【讨论】:

      猜你喜欢
      • 2011-05-07
      • 2011-07-13
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      相关资源
      最近更新 更多