Refactoring Redundant DAO

94 Views Asked by At

I have a DocDao which is configured with the docDataSource as below

docDataSource configuration from applicationContext.xml

<bean id="docDataSource"
    class="org.apache.tomcat.jdbc.pool.DataSource" 
    destroy-method="close"
    p:driverClassName="${doc.database.driver}" 
    p:url="${doc.database.url}"
    p:username="${doc.database.user}" 
    p:password="${doc.database.password}"
    p:validationQuery="select 1" 
    p:testOnBorrow="true" 
    p:minIdle="2" 
    p:maxIdle="4" 
    p:maxActive="6" 
    p:defaultTransactionIsolation="1">
</bean>

Below is my DAO class

@Component
public class DocDao implements GroovyInterceptable {

    @Autowired
    private Services services

    @Autowired
    @Qualifier("docDataSource")
    private DataSource            dataSource

    def conn

    def getConnection() {
        if (conn != null) return conn;
        conn = Sql.newInstance(dataSource)
        conn
    }
    // implementation for CRUD operations
}

I got a requirement to create a DAO with a different dataSource so I added a new bean customDocDataSource in applicationContext.xml as below

<bean id="customDocDataSource"
    class="org.apache.tomcat.jdbc.pool.DataSource" 
    destroy-method="close"
    p:driverClassName="${customDoc.database.driver}" 
    p:url="${customDoc.database.url}"
    p:username="${customDoc.database.user}" 
    p:password="${customDoc.database.password}"
    p:validationQuery="select 1" 
    p:testOnBorrow="true" 
    p:minIdle="2" 
    p:maxIdle="4" 
    p:maxActive="6" 
    p:defaultTransactionIsolation="1">
</bean>

And created a new DAO as below

@Component
public class CustomDocDao implements GroovyInterceptable {

        @Autowired
        private Services services

        @Autowired
        @Qualifier("customDocDataSource")
        private DataSource            dataSource

        def conn

        def getConnection() {
            if (conn != null) return conn;
            conn = Sql.newInstance(dataSource)
            conn
        }
        // implementation for CRUD operations
    }

The new CustomDAO works fine but it looks like a code smell. Can someone help me to refactor this and get a better implementation for CustomDocDao?

1

There are 1 best solutions below

0
On

If the only difference between DocDao and CustomDocDao is the dataSource, then you could simply instantiate the same class twice with different bindings.

For example, if you remove the @Component annotation and configure manually in your XML, you could do something like this:

<bean id="docDao" class="myPackage.DocDao" 
    p:dataSource-ref="docDataSource" />
<bean id="customDocDao" class="myPackage.DocDao" 
    p:dataSource-ref="customDocDataSource" />