Spring @Value annotation always evaluating as null?

前端 未结 6 1156
别跟我提以往
别跟我提以往 2020-12-05 09:33

So, I have a simple properties file with the following entries:

my.value=123
another.value=hello world

This properties file is being loaded

6条回答
  •  攒了一身酷
    2020-12-05 10:22

    You can also make your properties private, make sure your class is a Spring bean using @Service or @Component annotations so it always gets instantiated and finally add setter methods annotated with @Value . This ensures your properties will be assigned the values specified in your application.properties or yml config files.

    @Service
    public class Config {
        private static String myProperty;
    
        private static String myOtherProperty;
    
        @Value("${my.value}")    
        public void setMyProperty(String myValue) {
        this.myProperty = myValue;}
    
        @Value("${other.value}")
        public void setMyOtherProperty(String otherValue) {
        this.myOtherProperty = otherValue;}
    
        //rest of your code...
    }
    

提交回复
热议问题