我们有一个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
我们必须将其加载到自定义类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
}
我的弹簧启动配置文件如下:
@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);
}
}
单元测试是:
@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);
}
}
结果与预期不符。
@Value
类中删除DataSources
时,属性readDataSource
和writeDataSource
都为空(DataSources
类本身不为空)。< / LI>
当我在@Value
课程中添加DataSources
时,测试失败,异常
引起:java.lang.IllegalStateException:无法将[java.lang.String]类型的值转换为必需类型[com.abc.DataSource]:找不到匹配的编辑器或转换策略
感谢有人能提供一些如何处理这个问题的想法。我想要的只是在类似readDataSource
的类中捕获writeDataSource
和DataSources
。
答案 0 :(得分:6)
使用DataSources
为您的@Configuration
课程添加注释,然后创建使用@Bean
注释的2 @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();
}
}
现在您有2个数据源,其属性绑定到创建的DataSource
。 Spring Boot Reference Guide中的here解释了这种机制。
如果您不需要DataSource
但是构建自己的对象(虽然不确定为什么需要它?),这同样适用。