spring - @Value annotation not working in constructor

ID : 274481

viewed : 43

Tags : springspring

Top 4 Answer for spring - @Value annotation not working in constructor

vote vote


As far I remember, the value injection occurs after the constructor call.

Try to change your constructor to this:

public Email(@Value("${TO_EMAIL}") String toEmail) {     this.toEmail = toEmail; } 
vote vote


I encountered similar problems when I work with ApplicationRunner

public class AppStartupRunner implements ApplicationRunner {     @Autowired     private Environment myEnv; //not work      @value(${xxx.xxx})      private String myValue //not work      @Autowired     public AppStartupRunner(Environment env) {       System.out.println(myEnv); //null       System.out.println(myValue); //null     } } 

After I changed to the below codes, it works perfectly

  @Autowired   public AppStartupRunner(Environment env) {       env.getProperty("key") //works!   } 
vote vote


The value injection occures after the constructor call, to solve this in your case, you can leave the constructor empty. And add a method annotated with "@PostConstructor". This way, the empty constructor will be called, then the values will be injected, then the @PostConstructor method will be called.

vote vote


Top 3 video Explaining spring - @Value annotation not working in constructor