Spring Boot: @Value returns always null

后端 未结 5 655
既然无缘
既然无缘 2020-12-10 02:53

I would like to use a value from application.properties file in order to pass it in the method in another class. The problem is that the value returns always

5条回答
  •  鱼传尺愫
    2020-12-10 03:34

    Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

        @RestController 
    //or if you want to declare some specific use of the properties file then use
    //@Configuration
    //@PropertySource({"classpath:application-${youeEnvironment}.properties"})
    public class PropertyController {
    
        @Value("${name}")//not necessary
        private String name;//not necessary
    
        private static String NAME_STATIC;
    
        @Value("${name}")
        public void setNameStatic(String name){
            PropertyController.NAME_STATIC = name;
        }
    }
    

提交回复
热议问题