繁体   English   中英

Spring Boot - @Value 注释不起作用

[英]Spring Boot - @Value annotation doesn't work

我尝试使用 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;
    }
}

你猜对了,只有在对象被实例化后才会注入这些值; 因为弹簧容器不能设置尚不存在的东西的属性。 因此,在构造函数中,这些字段仍然为空。 一种解决方案是,要么

  1. 切换到构造器注入而不是设置器注入(YMMV,尚未测试您的用例)

或者

  1. 用带有@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;
    }
}

我试图通过MailService中的getter调用用户名和密码,并且显示了正确的值。 完成构造函数调用后,值可以访问吗?

将无参数构造函数代码移动到 PostConstruct 对我来说已经成功了。 因为它将保持默认的 bean 加载工作流完好无损。

试试这个解决方案。 https://stackoverflow.com/a/72547797/2002804

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM