carl_corder
carl_corder

Reputation: 143

Spring @Value property is null inside of custom pojo

I created a simple JavaMailSender spring-boot application (just for fun). Here is a reference to the code on GitHub:

https://github.com/carlcorder/mail.sender

I am having a problem where inside the Email class, the "from" property is null even though I annotate it with @Value (aside from that, everything works perfectly). The class is as follows:

package com.mail.sender.domain;

import lombok.NonNull;
import org.springframework.beans.factory.annotation.Value;

@lombok.Data
@lombok.AllArgsConstructor
@lombok.NoArgsConstructor
@lombok.Builder
public class Email {

    @NonNull
    private String to;

    @NonNull
    //@Value("{spring.mail.username}") --> this is always null
    private String from;

    @NonNull
    private String subject;

    private String body;

}

I have read these posts and understand the problem is most likely related.

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

and this:

Spring @Value annotation in @Controller class not evaluating to value inside properties file

However I was still unable to get anything working. Any help would be greatly appreciated.

Upvotes: 2

Views: 4329

Answers (1)

sag
sag

Reputation: 5461

As Deinum, mentioned in the comment, for non spring managed class, values will not be substituted.

In your case, since you are getting from as configuration, you can move the field to MailSenderService class.

There you need to declare the field with @Value annotation. Also as mentioned by @ndrone, the property name should be prefixed with $.

Add the below in MailSenderService and remove it from Email class

@Value("${spring.mail.username}")
private String from;

Upvotes: 2

Related Questions