Sir*_*tes 4 java spring annotations spring-boot
我尝试使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
您猜对了,只有在实例化对象之后,才会注入值。因为弹簧容器无法设置尚不存在的属性。因此,在构造器中,这些字段将仍然为null。一种解决方案是
要么
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4968 次 |
| 最近记录: |