Misleading wiring messages with aliased Spring DataSources

When accessing databases in Spring you commonly use a dataSource.xml file of some description to hold the XML stanzas describing the connection details to various databases or schemas.

When dealing with multiple dataSource requirements you might find that more than one logical dataSource bean name actually points to the same physical connection. Rather than define multiple datasource stanzas with exactly the same details, Spring allows the use of the element to point easily to an existing bean but use a different name:

<bean id="personDataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@database:port:SID" />
        <property name="username" value="USER" />
        <property name="password" value="PASS" />
        <property name="validationQuery" value="select 1 from dual"/>
    </bean>

    <alias alias="customerDataSource" name="personDataSource"/>
BUT (this is the whole point of this blog post really!)

If you get wiring errors when Spring tried to wire data sources into other beans it DOESN'T see aliased beans as first class citizens, when the error reports which data sources are available it won't list the aliased names, suggesting that you actually have less data sources than you really do!

So although aliases are great (and have saved me loads of lines of duplicated XML config) make sure you consider that they won't be shown in lists of 'available data sources'.

1 comment:

Noodle Soup said...

One way to get around this might be to define everything in an abstract bean using abstract="true", and then declare that as the parent of your other beans. That way, they're both fully fledged beans and you can even tweak individual properties on each concrete bean.