【问题标题】:Unable to use @Value annotation in Spring Boot [duplicate]无法在 Spring Boot 中使用 @Value 注释 [重复]
【发布时间】:2018-09-01 12:00:11
【问题描述】:

我有课

@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;
   ...
}

以及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...

但是当我启动应用程序时,出现以下异常:

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?

如何使用@Value 读取这些属性?

说实话,我已经尝试过多次使用@Value,但始终无法完全理解它。

【问题讨论】:

    标签: spring-boot


    【解决方案1】:

    使用$ 而不是#

    @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;
       ...
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-09
      • 1970-01-01
      • 2019-03-28
      • 2022-11-03
      相关资源
      最近更新 更多