Spring Boot application.properties value not populating

后端 未结 8 547
孤街浪徒
孤街浪徒 2020-12-04 11:41

I have a very simple Spring Boot app that I\'m trying to get working with some externalised configuration. I\'ve tried to follow the information on the spring boot documenta

相关标签:
8条回答
  • 2020-12-04 12:30

    The way you are performing the injection of the property will not work, because the injection is done after the constructor is called.

    You need to do one of the following:

    Better solution

    @Component
    public class MyBean {
    
        private final String prop;
    
        @Autowired
        public MyBean(@Value("${some.prop}") String prop) {
            this.prop = prop;
            System.out.println("================== " + prop + "================== ");
        }
    }
    

    Solution that will work but is less testable and slightly less readable

    @Component
    public class MyBean {
    
        @Value("${some.prop}")
        private String prop;
    
        public MyBean() {
    
        }
    
        @PostConstruct
        public void init() {
            System.out.println("================== " + prop + "================== ");
        }
    }
    

    Also note that is not Spring Boot specific but applies to any Spring application

    0 讨论(0)
  • 2020-12-04 12:34

    follow these steps. 1:- create your configuration class like below you can see

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.beans.factory.annotation.Value;
    
    @Configuration
    public class YourConfiguration{
    
        // passing the key which you set in application.properties
        @Value("${some.pro}")
        private String somePro;
    
       // getting the value from that key which you set in application.properties
        @Bean
        public String getsomePro() {
            return somePro;
        }
    }
    

    2:- when you have a configuration class then inject in the variable from a configuration where you need.

    @Component
    public class YourService {
    
        @Autowired
        private String getsomePro;
    
        // now you have a value in getsomePro variable automatically.
    }
    
    0 讨论(0)
提交回复
热议问题