我尝试使用 SmtpAuthenticator 创建邮件服务。组件已正确启动,但用户名和密码字段中存在空值。为什么?
@Component
public class SmtpAuthenticator extends Authenticator {
private static final Logger LOG =
LogManager.getLogger(SmtpAuthenticator.class.getSimpleName());
@Value("${spring.mail.username}")
private String username;
@Value("${spring.mail.password}")
private String password;
public SmtpAuthenticator() {
LOG.info(SmtpAuthenticator.class.getSimpleName() + " started...");
LOG.debug("username=" + username);
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
LOG.debug("Username and password are correct...");
return new PasswordAuthentication(username, password);
}
LOG.error("Not correct mail login data!");
return null;
}
}
你猜对了,只有在对象实例化之后,值才会被注入;因为 spring 容器无法设置尚不存在的属性。因此,在构造函数中,这些字段仍然为空。一种解决方案是
- 切换到构造函数注入 https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-spring-beans-and-dependency-injection.html而不是 setter 注入(YMMV,尚未测试您的用例)
Or
- 将构造函数替换为注释为的方法
@PostConstruct
。该方法将在注入过程之后执行。
例如
@Component
public class SmtpAuthenticator extends Authenticator {
private static final Logger LOG =
LogManager.getLogger(SmtpAuthenticator.class.getSimpleName());
@Value("${spring.mail.username}")
private String username;
@Value("${spring.mail.password}")
private String password;
@PostConstruct
public void init() {
LOG.info(SmtpAuthenticator.class.getSimpleName() + " started...");
LOG.debug("username=" + username);
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
LOG.debug("Username and password are correct...");
return new PasswordAuthentication(username, password);
}
LOG.error("Not correct mail login data!");
return null;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)