如何解决通过@Value 获取属性并以编程方式将其放入 application.yml 中 Java 与 SpringBoot
我使用 Azure KeyVault 来存储一些值。我需要获取这些值(例如 mysql-uri 或 client-secret)并在 application.yml(和 application-local.yml)中创建新属性。 首先,我尝试使用像 getDataSource 这样的 @Bean 创建 Configuration-class 来创建到数据库的连接,我成功了,但我还需要添加其他字段,例如 'oauth.client .秘密'。
所以我尝试在主类中获取值并创建“属性”,但是 @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”。
解决方法
你可以试试这种注入属性的方式。这使用了一个更简单的便利类 SpringApplication
而不是 SpringApplicationBuilder
。
MainClass.java
@SpringBootApplication
public class MainClass {
public static void main(String... args) {
SpringApplication.run(MainClass.class,args);
}
}
application.yaml 会被 Spring Boot 自动加载到上下文中(除非你已经针对它进行了配置)。属性可以重用、重新定义(使用配置文件),也可以使用系统/环境变量。
注意 Spring 配置非常灵活和强大。请阅读此文档https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config
application.yaml
app:
name: Demo
oauth:
client:
secret: ${app.name} // This will have "Demo"
env:
path: ${SOME_ENV_VAR} // This will take SOME_ENV_VAR from env variable
SomeService.java
@Service
public class SomeService {
@Value("${app.name})
private String appName;
public void printAppName() {
log.info(appName); // will log the appname
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。