java - 如何在 Spring Boot 中从根键读取值
问题描述
我正在尝试从 rootKey 读取应用程序配置,但我得到了空值。
rootKey1:
childKey1: childValue1
childKey2: childValue2
childKey3: childValue3
rootKey2:
childKey1: childValue1
childKey2: childValue2
childKey3: childValue3
Environment environment;
getProperty(String key) {
environment.getProperty(key+".childKey1"); --> is giving childValue1
-------------------
environment.getProperty(key); --> is giving null
}
更正: rootKey 是动态的。
解决方案
尝试定义您的属性对象结构并注册一个适当的 bean。
@SpringBootApplication
public class DemoApplication implements ApplicationRunner {
@Data
public static class RootProperty {
private List<ChildProperty> list;
}
@Data
public static class ChildProperty {
private String name;
private String childKey1;
private String childKey2;
private String childKey3;
}
@Autowired
private ApplicationContext context;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
@ConfigurationProperties("root-key")
public RootProperty rootProperty() {
return new RootProperty();
}
@Override
public void run(ApplicationArguments args) {
System.out.println(context.getBean("rootProperty"));
}
}
应用程序.yml
root-key:
list:
- name: child-key1
childKey1: childValue1-1
childKey2: childValue1-2
childKey3: childValue1-3
- name: child-key2
childKey1: childValue2-1
childKey2: childValue2-2
childKey3: childValue2-3
推荐阅读
- objective-c - 10.9 中的 NSScrollView 辅助功能问题
- php - PHP 如何让我的 csv 表正确显示?
- c - 将用户输入与 C 编程语言中预定义的字符数组进行比较
- python - 在 Python 上使用 scipy.least_squares 进行正弦波频率估计
- json - 如何在颠簸中保持空值的条件?
- ruby-on-rails - Ajax 请求速度问题
- annotations - 在 konvajs 中添加另一个形状时会显示所有以前的形状
- android - 如何在 Android 中将 protobuf 转换为 POJO/JSON
- android - Glide 与 Room 数据库的集成,GlideApp 类未生成(Glide 4.7.1)
- asp.net-web-api - 如何从我的 asp.net Web API 触发 App Center Push?