【问题标题】:Spring Boot - @Value annotation doesn't workSpring Boot - @Value 注释不起作用
【发布时间】:2018-03-03 03:10:18
【问题描述】:

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

【问题讨论】:

  • 您是否在application 属性/yaml 文件中定义了属性spring.mail.usernamespring.mail.password

标签: java spring spring-boot annotations


【解决方案1】:

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

  1. 切换到 constructer Injection 而不是 setter Injection(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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2019-12-18
    • 2017-05-22
    • 2015-09-01
    • 2019-06-15
    • 2019-07-03
    相关资源
    最近更新 更多