我尝试使用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; } }
您猜对了,只有在实例化对象之后,才会注入值。因为弹簧容器无法设置尚不存在的属性。因此,在构造器中,这些字段将仍然为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; } }