首页 > 解决方案 > 有没有办法从 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。

标签: springspring-boot

解决方案


@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

然后在应用程序启动之后,您可以AutowireApplicationProps 并从 restTemplateConfigurations 列表中检索您喜欢的任何内容。


推荐阅读