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                   = [email protected]
mail.password               = mypassword

# Sending Email
mail.smtp.host              = smtp.gmail.com
mail.from                   = [email protected]
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.

0

1 Answer 1

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. #)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.