【发布时间】:2021-04-09 07:34:28
【问题描述】:
我正在使用BeanFactoryPostProcessor 在运行时创建 Rest Templates bean。其余模板的配置放在一个 yml 文件中。
config:
banks:
A1:
restTemplate:
connectTimeout: 16000
socketTimeout: 18000
maxPerRoute: 10
maxTotalConnection: 20
B1:
restTemplate:
connectTimeout: 20000
socketTimeout: 20000
maxPerRoute: 10
maxTotalConnection: 2
A1、B1 是动态的。属性文件可能有 C1、D1 等。我实现了EnvironmentAware
.但它只能获得类似的属性
environment.getProperty("config.banks.A1.restTemplate.connectTimeout");
有没有办法以 dto 的形式获取这些动态属性,类似于使用@ConfiguratioProperties
我什至尝试了以下方法:
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new FileSystemResource(environment.resolvePlaceholders("${catalina.home}") + "/conf/restTemplate_prop.yml"));
bean.afterPropertiesSet();
Properties props = bean.getObject();
Enumeration names = props.propertyNames();
while (names.hasMoreElements()) {
String name = names.nextElement().toString();
String value = props.getProperty(name);
}
但我得到的属性为:
我什至没有得到所有的属性。有没有办法在 dto 中获取属性,有没有一种有效的方法来做到这一点? 注意:我目前使用的是 Spring Boot 1.5.2 版,所以我没有 Binder API。
【问题讨论】:
-
不在
BeanFactoryPostProcessor中,因为它在 Spring 或 Spring Boot 读取属性之前执行。因此,您需要手动加载并绑定到 DTO。同样尝试使用PropertiesLoader加载 YAML 文件显然不起作用,它不是属性文件而是 YAML 文件。如果有什么需要YamlPropertiesFactoryBean加载并将其解析为Properties对象。
标签: spring spring-boot