14

Is there an XML equivalent of @Primary that can promote one of the multiple qualifying beans

Example Scenario:

I've a spring-boot application with auto-configuration turned on. I've defined multiple datasources, however spring is unable to pick one of the datasources as its default.

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>
Monish Sen
  • 1,773
  • 3
  • 20
  • 32

1 Answers1

24

<bean> property has primary attribute:

<bean primary="true|false"/>

And remember:

If a @Primary-annotated class is declared via XML, @Primary annotation metadata is ignored, and <bean primary="true|false"/> is respected instead.

Mykola Yashchenko
  • 5,103
  • 3
  • 39
  • 48