首页 > 解决方案 > @Value 为一个班级工作,但不是另一个班级

问题描述

我在我的 API 中使用 @Value 注释苦苦挣扎。

我的值存储在 Spring Boot 的 application.properties 文件中。

secretKey=trullySecretKey

我为 JWT 密钥创建了一个 @Component 类:

@Component
public class SecretKeyProperties {

@Value("${secretKey}")
private String secretKey;

public String getSecretKey() {
    return this.secretKey;
}

}

并使用它作为我的 JWT 类:

@Service
public class JwtUtil {

@Autowired
SecretKeyProperties secretKeyProperties;

private Claims extractAllClaims(String token) {
    return Jwts.parser().setSigningKey(secretKeyProperties.getSecretKey()).parseClaimsJws(token).getBody();
}...

工作正常。

但是当我做同样的事情,但使用邮件属性设置的组件时:

    #Mail properties

auth=mail.smtp.auth
authValue=true
starttls=mail.smtp.starttls.enable
starttlsValue = true
host=mail.smtp.host
hostValue=smtp.gmail.com
ssl=mail.smtp.ssl.enable
sslValue=true
sender=test@email.com
password=myPassword

班上:

@Component
public class MailProperties {

@Value("${auth}")
private String auth;

@Value("${starttls}")
private String starttls;

@Value("${host}")
private String host;

@Value("${ssl}")
private String SSL;

@Value("${authValue}")
private boolean authValue;

@Value("${starttlsValue}")
private boolean starttlsValue;

@Value("${hostValue}")
private String hostValue;

@Value("${sslValue}")
private boolean sslValue;

@Value("${sender}")
private String sender;

@Value("${password}")
private String password;


public String getAuth() {
    return this.auth;
}

public String getStarttls() {
    return this.starttls;
}

public String getHost() {
    return this.host;
}

public String getSsl() {
    return this.ssl;
}

public boolean getAuthValue() {
    return this.authValue;
}

public boolean getStarttlsValue() {
    return this.starttlsValue;
}

public String getHostValue() {
    return this.hostValue;
}

public boolean getSslValue() {
    return this.sslValue;
}

public String getSender() {
    return this.sender;
}

public String getPassword() {
    return this.password;
}

和实施:

@Service
public class MessageBuilder {

@Autowired
MailProperties mailProperties;

public static Properties properties;
public static Session session;

public Properties setupProperties(){
    Properties properties = new Properties();
    
    properties.put(mailProperties.getAuth(), mailProperties.getAuthValue());
    properties.put(mailProperties.getStarttls(), mailProperties.getStarttlsValue());
    properties.put(mailProperties.getHost(), mailProperties.getHostValue());
    properties.put(mailProperties.getSsl(), mailProperties.getSslValue());

    return properties;
}

我收到一个错误

 Cannot invoke "com.plaincoded.restapi.configuration.MailProperties.toString()" because "this.mailProperties" is null

如果它在两种情况下都不起作用,而仅在一种情况下起作用,那是否有意义?

为什么会这样?

更新:

文件夹结构

标签: javaspring-bootannotations

解决方案


推荐阅读