Why is Spring @Value
Annotation not working in the constructor?
I have this Email
class that is reading some email related configuration.
In the constructor, if I put a break-point the values are empty.
But if I call the sendEmail
method, there are values.
Other Class:
@Autowired
Email sender;
Email
Class:
@Component
public class Email{
@Value("${TO_EMAIL}")
private String toEmail;
public Email() {
// Here toEmail is null
}
public void sendEmail(String subject, String body) {
// Here toEmail has value
}
}
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;
}