我有一个班级
@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,但却永远无法完全理解它。
答案 0 :(得分:3)
使用$
代替#
@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;
...
}