我遵循了关于创建多个数据源的多篇文章,并在我的代码中尝试了相同的方法。但是奇怪的是,spring只初始化一个数据源而不初始化另一个数据源。当我从代码中删除其中任何一个时,另一个就会毫无问题地创建。任何想法。
Bean配置-
@Configuration
public class DBConfiguration {
@Bean("dataSource")
@ConfigurationProperties(prefix = "p.datasource")
public DataSource pDataSource() {
System.out.println("**************************> dataSource");
return DataSourceBuilder.create().build();
}
@Bean("storeFrontDataSource")
@ConfigurationProperties(prefix = "c.datasource")
public DataSource cDataSource() {
System.out.println("**************************> storeFrontDataSource");
return DataSourceBuilder.create().build();
}
}
YML文件(为了保密删除了一些数据)-
p:
datasource:
url: {some-url}
driver-class-name: com.ibm.db2.jcc.DB2Driver
username: abc
password: xyz
type: com.zaxxer.hikari.HikariDataSource
hikari:
schema:
connection-init-sql: select 1 from dual
minimum-idle: 25
maximum-pool-size: 100
idle-timeout: 10_000
max-lifetime: 20_000
connection-timeout: 1_000
validation-timeout: 500
c:
datasource:
url: {some-url}
driver-class-name: com.ibm.db2.jcc.DB2Driver
username: abc
password: xyz
type: com.zaxxer.hikari.HikariDataSource
hikari:
schema:
pool-name: uspo-cis-sf-pool
connection-init-sql: select 1 from dual
minimum-idle: 1
maximum-pool-size: 5
idle-timeout: 10_000
max-lifetime: 50_000
connection-timeout: 2_000
validation-timeout: 500
抛出错误-
仅限"数据源";bean,而不是"storeFrontDataSource"bean。即使在控制台上,也只调用System.out.println()中的一个(即用于"datasource"),而不打印其他的。SpringBoot甚至没有初始化其他bean定义。
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.zaxxer.hikari.HikariDataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=storeFrontDataSource)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1790) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1346) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791) ~[spring-beans-5.3.3.jar:5.3.3]
... 38 common frames omitted
注意-即使定义@Primary也没有帮助。无论如何,System.out.println()都应该打印到控制台。
根据建议@tgdavies,我发现来自依赖库的一些类正在注入'HikariDataSource'而不是'DataSource'。
您需要为创建多个数据源创建客户配置类,并定义主数据源。
查看baeldung
中的示例