什么配置可以评估@Value注释?

时间:2015-08-10 08:06:00

标签: spring

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

我正在使用@Value:

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

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

我需要将哪些内容添加到Configuration类才能启用此行为?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

根据ShadowRay的回答,启用请求行为的最小代码是:

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

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