Search code examples
javaspringdependency-injectionstatic-initialization

How to inject system property into static bean in configuration?


In my Spring @Configuration class I wish to inject the system property ${brand} into a static String bean called brandString. I have succeeded doing that with the workaround described here https://stackoverflow.com/a/19622075/1019830 using @PostConstruct and assigning the static field an instance field value injected through @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() {...}

Is there another way of statically inject the value of ${brand} into the brandString field, without the workaround using another "copy" brand and a @PostConstruct method?


Solution

  • Try this:

    @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;
        }
    ...
    }