[英]Qualifier doesn't work for DataSource in Spring Boot
我有两个数据源定义为“ datasource1”和“ datasource2”(在依赖项的xml配置中)。 因此,默认情况下我没有配置JdbcTemplate,所以我需要手动进行操作,如下所示:
1。
@Bean
public JdbcOperations jdbcOperations(DataSource datasource1) {
return new JdbcTemplate(datasource1);
}
2。
@Bean
public JdbcOperations jdbcOperations(@Qualifier("datasource1") DataSource datasource1) {
return new JdbcTemplate(datasource1);
}
在两种情况下,它均失败:
Parameter 0 of method jdbcOperations in com.example.PersistentConfig required a single bean, but 2 were found:
- datasource1: defined in class path resource [datasources.xml]
- datasource2: defined in class path resource [datasources.xml]
为什么预选赛不起作用?
我无法更改datasources.xml
文件以将primary=true
添加到datasource
。
datasources.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="datasource1"
class="com.example.database.IdentifiedLazyConnectionDataSourceProxy">
<qualifier value="datasource1"/>
<property name="targetDataSource">
<bean class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/ak1Database"/>
<property name="resourceRef" value="true"/>
</bean>
</property>
<property name="identifier" value="shared"/>
</bean>
<bean id="datasource2"
class="com.example.database.IdentifiedLazyConnectionDataSourceProxy">
<qualifier value="datasource2"/>
<property name="targetDataSource">
<bean class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/ak2Database"/>
<property name="resourceRef" value="true"/>
</bean>
</property>
<property name="identifier" value="shared"/>
</bean>
</beans>
这不起作用的原因是因为xml配置始终会覆盖Java配置(请参阅https://jira.spring.io/browse/SPR-7028 )。
为了解决这个问题,我需要创建一个名称与xml中名称不同的bean,并将新bean标记为@Primary
。
因此,现在我将拥有三个数据源bean,其中两个连接到相同的数据库模式,但是只有一个标记为Primary,因此它将在默认位置使用,而不是在xml定义的位置使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.