Property values in bean class are null in constructor

前端 未结 2 608
逝去的感伤
逝去的感伤 2020-12-19 11:01

I\'m trying to use values from my application.properties file in my service implementation class/bean. But when the bean is initialized through my config class, the property

相关标签:
2条回答
  • 2020-12-19 11:48

    Those values are injected after the instance is created. So they are null in the constructor.

    To execute a method after the values are injected use @javax.annotation.PostConstruct:

    @PostConstruct
    public void init(){ // method name doesn't matter
         functionOne(value_one, value_two, value_three);
    }
    
    0 讨论(0)
  • 2020-12-19 11:58

    If you use the values in the constructor they won't be available right away. Indeed they are injected on attribute. What's happening here is after spring created an instance then it will update the attribute value.

    If you want to use those values in the constructor you should use constructor injection. Injection by constructor is a best practice.

    public class AppServiceImpl implements AppService {
        String value_one;
        String value_two;
        String value_three;
    
        //values are null here
        public AppServiceImpl(String value1, String value2, String value3) {
            value_one = value1;
            value_two = value2;
            value_three = value3;
            functionOne(value_one, value_two, value_three);
        }
    }
    

    And your configuration class

    @Configuration
    public class AppConfig {
        @Bean AppServiceImpl appServiceImpl(@Value("${value.one}") String value1,  @Value("${value.two}") String value2,  @Value("${value.three}") String value3) {
            return new AppServiceImpl(value1, value2, value3);
        }
    }
    
    0 讨论(0)
提交回复
热议问题