spring通过@Value获取属性并将其应用到应用程序中。yml编程。带SpringBoot的Java
我使用Azure KeyVault来存储一些值。我需要获取这些值(例如,mysql uri或client secret),并在应用程序中创建新属性。yml(和applicationlocal.yml)。 首先,我尝试使用像getDataSource这样的@Bean创建配置类来创建到数据库的连接,我成功地做到了,但我还需要添加其他字段,例如“oauth”。客户秘密'
所以我尝试在主类中获取值并创建“属性”,但是@Value不能是静态的,这个解决方案抛出NPE。我试图创建新的配置类并从中获取属性,然后将其拉入SpringApplicationBuilder
,但我需要ApplicationContext(因此将调用SpringApplication.run
)来获取该类的一个实例(bean)和值
我不知道下一步该怎么办,我被卡住了。准备好重写并展示您需要的任何解决方案
更新1:
@Value("${secret}")
private String clientSecret;
public static void main(String[] args) {
new SpringApplicationBuilder(DefaultApplication.class).properties(getProperties()).run(args);
}
@NotNull
private static Properties getProperties() {
Properties properties = new Properties();
properties.put("oauth.client.secret", Objects.requireNonNull(clientSecret));
return properties;
}
clientSecret出现错误:无法从静态上下文引用非静态字段“clientSecret”
# 1 楼答案
您可以尝试这种注入属性的方法。这使用了一个更简单的便利类
SpringApplication
,而不是SpringApplicationBuilder
main类。java
应用程序。yaml将通过Spring Boot自动加载到上下文中(除非您针对它进行了配置)。可以重用、重新定义属性(使用概要文件),也可以使用系统/环境变量
注意弹簧配置非常灵活且功能强大。请阅读此文档https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config
应用程序。yaml
一些服务。java