简体   繁体   English

如何在Spring Boot应用程序中从YML文件加载多个属性

[英]How to load multiple properties from YML file in spring-boot application

We have a YML configuration which looks like: 我们有一个YML配置,如下所示:

datasurces: 
  readDataSource:
    ssl-enabled: false
    driver-class-name: oracle.jdbc.driver.OracleDriver
    host: db1.abc.com
    port: 1232
    sid: ABC_DB
    trust-store-fileName: abcdb.jks
    connection-pool:
      initial-size: 10
      max-size: 20

  writeDataSource:
    ssl-enabled: false
    driver-class-name: oracle.jdbc.driver.OracleDriver
    host: db2.abc.com
    port: 1232
    sid: XYZ_DB
    trust-store-fileName: xyzdb.jks
    connection-pool:
      initial-size: 10
      max-size: 20

We have to load this to a custom class DataSources which looks like 我们必须将其加载到自定义类DataSources ,该类看起来像

@ConfigurationProperties(prefix = "datasources")
public class DataSources {
  @Value("${datasources.readDataSource}")
  private DataSource readDataSource;

  @Value("${datasources.writeDataSource}")
  private DataSource writeDataSource;

  //...getters/setters
}

public class DataSource {
  private String id;
  private boolean sslEnabled;
  private String driverClassName;
  private String host;
  private int port;
  private String trustStoreFileName;
  private ConnectionPool connectionPool;

  //...getters/setters  
}

public class ConnectionPool {
  private int initialSize;
  private int maxSize;

  //...getters/setters 
}

My configuration files for spring boot looks like: 我的Spring Boot配置文件如下所示:

@Configuration
@ComponentScan(basePackages = {"com.abc"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableConfigurationProperties(DataSources.class)
@Profile({"dev"})
public class TestAppConfiguration {

}

@EnableAutoConfiguration
@SpringBootApplication
@EnableConfigurationProperties(DataSources.class)
public class TestAppInitializer {
  @Autowired
  private DataSources dataSources;

  public static void main(final String[] args) {
    SpringApplication.run(TestAppInitializer.class, args);
  }
}

The unit test is: 单元测试是:

@SpringApplicationConfiguration(classes = {TestAppInitializer.class})
@Test(groups = "categoryTests")
@ActiveProfiles("dev")
public class DataSourcesTest extends AbstractTestNGSpringContextTests {
  private static final AppLogger logger = LoggerUtil.getLogger(DataSourcesTest.class);

  @Autowired
  private DataSources dataSources;

  @Test
  public void printDetails() {
    logger.debug("DataSources --> {}", dataSources);
  }
}

Result is not as expected. 结果不符合预期。

  1. When I remove @Value from DataSources class, both the properties readDataSource and writeDataSource are null (The DataSources class itself is not null). 当我从DataSources类中删除@Value ,属性readDataSourcewriteDataSource都为null( DataSources类本身不为null)。
  2. When I add @Value in DataSources class, the test fails with exception 当我在DataSources类中添加@Value时,测试失败并出现异常

    Caused by: java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.abc.DataSource]: no matching editors or conversion strategy found 原因:java.lang.IllegalStateException:无法将类型[java.lang.String]的值转换为所需的类型[com.abc.DataSource]:未找到匹配的编辑器或转换策略

Appreciate if someone can provide some idea how to deal with this. 欣赏是否有人可以提供一些解决方法。 All I want is to capture both readDataSource and writeDataSource inside a class like DataSources . 我想要的是在类似DataSources的类中捕获readDataSourcewriteDataSource

Annotate your DataSources class with @Configuration then create 2 @Bean methods annotatated with @ConfigurationProperties . 注释你的DataSources@Configuration再创建2种@Bean与annotatated方法@ConfigurationProperties

@Configuration
public class DataSources {

    @Bean
    @ConfigurationProperties(prefix="datasources.readDataSource")
    public DataSource readDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix="datasources.writeDataSource")
    public DataSource writeDataSource() {
        return DataSourceBuilder.create().build();
    }
}

Now you have 2 datasources with the properties bound to the created DataSource s. 现在,您有2个数据源,其属性绑定到创建的DataSource This mechanism is explained here in the Spring Boot Reference Guide. 这种机制被解释这里的春天引导参考指南中。

The same would apply if you don't need a DataSource but construct your own object (although not sure why you would need that?). 如果您不需要DataSource而是构造自己的对象(尽管不确定为什么会需要它),则同样适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 spring-boot 应用程序中的 application.yml 文件中读取属性 - How to read properties from application.yml file in spring-boot application 如何从其他文件加载基于Spring-boot的REST应用程序属性? - how to load spring-boot based REST application properties from a different file? 从 spring-boot 中的 application.yml 文件中获取 cron - Get cron from application.yml file in spring-boot 从json文件加载spring-boot属性 - Load spring-boot properties from json file Spring Boot - 从依赖的 jar 加载 application.properties/yml - Spring Boot - Load application.properties/yml from dependent jar spring-boot如何添加多个application.properties文件? - How to add multiple application.properties files in spring-boot? 无法从spring-boot中的Properties文件和Bootstrap.yml中选择值 - Unable to pick the values from Properties file and Bootstrap.yml in spring-boot 从 spring-boot 中的 properties.yml 文件中读取字符串数组数据 - Reading String array data from properties.yml file in spring-boot 如何在Spring Boot应用程序中使用配置(properties / yml)文件中的属性? - How can I use properties from a configuration (properties/yml) file in my Spring Boot application? 您如何配置prometheus.yml文件以在Spring-Boot应用程序中收集Prometheus指标? - How do you configure prometheus.yml file to collect Prometheus metrics in a Spring-Boot application?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM