java - @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
如果它在两种情况下都不起作用,而仅在一种情况下起作用,那是否有意义?
为什么会这样?
更新:
解决方案
推荐阅读
- c++ - 如何在 Makefile 中为两组文件使用不同的规则?
- excel - 使用宏今天和过去日期过滤日期
- css - Google Chrome 滚动捕捉中的潜在错误
- typescript - 如何键入函数的静态成员?
- docker - 如何使用 docker compose 在 angular 和 spring 之间进行通信
- java - 带有验证的 Kafka Connect JsonConverter
- python - 如何录制视频并从网络摄像头保存?
- c# - 发布到 IIS 上的 ASP.NET Core 应用程序无法识别 AD 用户
- c# - 在 Main 方法中等待 - 在任务完成之前谁获得控制权?
- javascript - 循环遍历复杂的反应状态以删除所有空字符串