2

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.

Community
  • 1
  • 1
carl_corder
  • 143
  • 3
  • 12
  • 1
    Forgot the `$` in front `${spring.mail.username}` – ndrone Jul 08 '16 at 02:55
  • 3
    Ofcourse it will be `null`. It isn't a spring managed class but an object created outside of that scope (by the Spring mVC classes for binding your JSON). Those objects don't get processed and as such `@Value` won't work. Also why would you want that property on your email class, it should belong in your service as a property not as part of the object that is passed in. – M. Deinum Jul 08 '16 at 06:40
  • Ok, thanks for you explanation. I thought that property best belonged with the Email domain object because the spring MailProperties username property would always be the value passed from application.properties. By setting the "from" field on the Email object with this value that it would be more explicit that this field will/should only every have one value which comes from the properties file. – carl_corder Jul 08 '16 at 13:53

1 Answers1

2

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;
sag
  • 5,333
  • 8
  • 54
  • 91