Spring XML相当于@Primary

时间:2017-08-07 13:45:11

标签: java xml spring

是否有 @Primary 的XML等效项可以提升多个符合条件的bean之一

示例场景:

我启用了自动配置的spring-boot应用程序。我已经定义了多个数据源,但是spring无法选择其中一个数据源作为默认数据源。

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] is defined: expected single matching bean but found 2: mysqlDataSource,oracleDataSource

datasources.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jdbc
        http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">

    <bean id="mysqlDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/mcs" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>


    <bean id="oracleDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:test" />
        <property name="username" value="scott" />
        <property name="password" value="tiger" />
    </bean>

    <bean id="transactionManager"
    class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />

</beans>

1 个答案:

答案 0 :(得分:10)

<bean>属性具有primary属性:

<bean primary="true|false"/>

请记住:

  

如果通过XML @Primary注释声明了@Primary - 带注释的类   忽略元数据,并尊重<bean primary="true|false"/>   代替。