2015-06-08 86 views
0

我有配置了docDataSource如下重構冗餘DAO

docDataSource配置從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> 

下面一個DocDao是我DAO類

@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 
} 

我有一個要求,用不同的dataSource創建一個DAO,所以我在applicationContext.xml中添加了一個新的bean customDocDataSource,如下所示

<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> 

並創建一個新的DAO如下

@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 
    } 

新CustomDAO工作正常,但它看起來像一個代碼味道。有人可以幫助我重構這個並獲得更好的實現CustomDocDao

+0

@Opal對不起,是我不好..!忘了接受... – RanPaul

+0

不用擔心,謝謝! – Opal

回答

1

如果DocDaoCustomDocDao之間的唯一區別是dataSource,那麼您可以簡單地使用不同的綁定實例化相同的類兩次。

例如,如果您刪除@Component註釋和您的XML手動配置,你可以做這樣的事情:

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