1

I have a class

@Component
@Configuration
public class EmailSender {

    private Properties properties;
    @Value("#{mail.smtp.starttls.enable}") private String startTls;
    @Value("#{mail.transport.protocol}") private String protocol;
    @Value("#{mail.smtp.auth}") private String auth;
    @Value("#{mail.smtp.host}") private String host;
    @Value("#{mail.user}") private String user;
    @Value("#{mail.password}") private String password;
   ...
}

And the following properties in application.properties

# Email Credentials
mail.user                   = someone@somewhere.com
mail.password               = mypassword

# Sending Email
mail.smtp.host              = smtp.gmail.com
mail.from                   = someone@somewhere.com
mail.smtp.starttls.enable   = true
mail.transport.protocol     = smtp
mail.smtp.auth          = true
mail.subject            = my subject...

But when I start the application, I get the following exception:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'emailSender': Unsatisfied dependency expressed through field 'startTls'; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'mail' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?

How can I read these properties using @Value?

To be honest I've tried many times to use @Value but can never see to quite get it.

NickJ
  • 9,380
  • 9
  • 51
  • 74

1 Answers1

4

Use property reference with $ instead of SpEL expression with #

@Component
@Configuration
public class EmailSender {

    private Properties properties;
    @Value("${mail.smtp.starttls.enable}") private String startTls;
    @Value("${mail.transport.protocol}") private String protocol;
    @Value("${mail.smtp.auth}") private String auth;
    @Value("${mail.smtp.host}") private String host;
    @Value("${mail.user}") private String user;
    @Value("${mail.password}") private String password;
   ...
}

You can read more about $ vs. # in the question Spring Expression Language (SpEL) with @Value: dollar vs. hash ($ vs. #)

MiB
  • 575
  • 2
  • 10
  • 26
Pankaj Gadge
  • 2,748
  • 3
  • 18
  • 25