如何在配置中将系统属性注入静态bean?

时间:2014-08-07 11:07:28

标签: java spring dependency-injection static-initialization

在我的Spring @Configuration类中,我希望将系统属性${brand}注入名为brandString的静态String bean中。我使用@PostConstruct成功地使用https://stackoverflow.com/a/19622075/1019830中描述的解决方法,并为静态字段指定了通过@Value注入的实例字段值:

@Configuration
public class AppConfig {

  @Value("${brand}")
  private String brand;
  private static String brandString;

  @PostConstruct
  public void init() {
    brandString = brand;
  }

  @Bean
  public static String brandString() {
    return brandString;
  }

  // public static PropertyPlaceHolderConfigurer propertyPlaceHolderConfigurer() {...}

是否有另一种方法可以将${brand}的值静态注入brandString字段,而无需使用其他" copy" brand@PostConstruct方法?

1 个答案:

答案 0 :(得分:1)

试试这个:

@Configuration
public class AppConfig {

    private static String brand;

    @Value("${brand}")
    public void setBrand(String brand) {
        AppConfig.brand = brand;
    }

    @Bean
    public static String brandString() {
        return brand;
    }
...
}