spring - 有没有办法从 BeanFactoryPostProcessor 中读取属性文件?
问题描述
我正在使用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。
解决方案
@Component
@ConfigurationProperties(prefix = "config.banks.restTemplate")
public class ApplicationProps {
private List<Map<String, Object>> props;
private List<RestTemplateConfiguration> restTemplateConfigurations;
// getters and setters
public static class RestTemplateConfiguration {
private String name;
private Integer connectTimeout;
private Integer socketTimeout;
private Integer maxPerRoute;
private Integer maxTotalConnection
// getters and setters
}
}
然后让你的 yaml 包含复杂属性的列表
config:
banks:
restTemplate:
-
name: A1
connectTimeout: 16000
socketTimeout: 18000
maxPerRoute: 10
maxTotalConnection: 20
-
name: B1
connectTimeout: 20000
socketTimeout: 20000
maxPerRoute: 10
maxTotalConnection: 2
然后在应用程序启动之后,您可以Autowire
ApplicationProps 并从 restTemplateConfigurations 列表中检索您喜欢的任何内容。
推荐阅读
- python - 将复杂的 XML 文件转换为 Pandas 数据框/CSV - Python
- python - 如何在python中查找文本图像的图像相似度
- python - python streamlit运行问题
- javascript - 如何动态创建页脚列
- python-3.x - 带有条件的 Pandas DataFrame 副本
- javascript - 功能组件中的 setState 不保留值
- elasticsearch - 升级弹性客户端和依赖项以连接到较旧的弹性服务器实例
- docker - 在使用 Kubernetes 部署的浏览器上看不到我的应用
- python-3.x - 需要一个类似字节的对象,而不是“str”(不发送到 dataOutput)
- azure-files - 从 Windows 10 PC 连接到 Azure 文件共享时出错