java - 为什么我不能访问带有 @SpringBootApplication 注释的主文件之外的 application.properties 值?
问题描述
我的 Spring Bootapplication.properties
文件中有一个自定义的键值对:
jwt.secret=secretkey
我在与运行器类相同的目录中为此属性创建了一个配置类:
@Configuration
@ConfigurationProperties(prefix = "jwt")
@PropertySource("classpath:application.properties")
public class JwtProperties {
/**
* Secret key used to sign JSON Web Tokens
*/
private String secret = "";
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
正如预期的那样,我可以ServerApplication.java
使用@Value
注释在我的主 Spring runner 类中访问这个值:
@SpringBootApplication
@EnableConfigurationProperties(JwtProperties.class)
public class ServerApplication implements CommandLineRunner {
@Value("${jwt.secret}")
String test;
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
// correctly prints "test is: secretkey"
System.out.println("test is " + test);
}
}
我有一个类/security/JwtClient.java
,我希望能够使用这个jwt.secret
属性,但我无法让@Value
注释工作(它总是产生一个null
字符串):
@Component
public class JwtClient {
@Value("${jwt.secret}")
private String secretKey;
public String buildJWT(Customer customer) {
// incorrectly prints "secret key: null"
System.out.println("secret key: " + secretKey);
// attempts to build JSON Web Token here but secret key is missing
}
}
我已经阅读了许多有关此主题的 StackOverflow 问题,但几乎所有问题似乎都认为@Value
注释将在@Component
-annotated 类上正常工作。我在这里想念什么?
解决方案
推荐阅读
- postman - 如何在不是查询参数的邮递员端点 URL 中使用数据变量?
- python - 使用python进行高斯拟合
- amazon-web-services - AWS CDK、ecs-patterns、ApplicationLoadBalancedFargateService、设置标签
- oop - 为什么 Dart 更喜欢省略局部变量的类型注释?
- c# - 如何格式化 DataGrid 中的单元格以在之后显示 % 符号
- html - GTranslate Wordpress 插件在手机上无法正常工作
- java - Thymeleaf 模板找不到相关的 JS、CSS 和 i18n 文件
- javascript - Firebase 功能测试初始化失败
- mybatis - mybatis 3 + spring:我可以根据查询结果中的列值将集合结果分为两组吗
- html - 安全的 HTML 到 PDF