2013-02-16 20 views
0

我想從我的context.xml文件注入數據源。我有這個配置文件,但問題是,我有隨時多個數據源。當我嘗試注入其中任何一個,我得到的說,有一個不匹配豆錯誤。 這是我的代碼。從春天注入/自動裝配數據源時,多個數據源中指定

@Inject 
    @Named("dataSourceAccounts") 
    //@Autowired 
    @Override 
    public void setDataSource(DataSource dataSource) { 
     // TODO Auto-generated method stub 
     this.jdbcTemplate = new JdbcTemplate(dataSource); 
     System.out.println("jdbcTemplate is null? " + (jdbcTemplate == null)); 

    } 

//for the context.xml 
<context:component-scan base-package="business" /> 
    <context:component-scan base-package="middleware" /> 
    <context:component-scan base-package="presentation" /> 
    <context:annotation-config/> 

    <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" /> 
    <bean id="txManagerProducts" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
     <property name="dataSource" ref="dataSourceProducts"/> 
    </bean > 
    <bean id="txManagerAccounts" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
     <property name="dataSource" ref="dataSourceAccounts"/> 
    </bean > 

    <bean id="dataSourceProducts" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 
     <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
     <property name="url" value="jdbc:mysql://localhost:3306/productsdb" /> 
     <property name="username" value="root" /> 
     <property name="password" value="root" /> 
    </bean> 
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 
     <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
     <property name="url" value="jdbc:mysql://localhost:3306/accountsdb" /> 
     <property name="username" value="root" /> 
     <property name="password" value="root" /> 
    </bean> 

感謝您的提前幫助。

回答

2

如果你想爲應注射的依賴性指定合格的名稱,@Named應先帕拉姆定義:

@Inject 
@Override 
public void setDataSource(@Named("dataSourceAccounts") DataSource dataSource) { 
    // TODO Auto-generated method stub 
    this.jdbcTemplate = new JdbcTemplate(dataSource); 
    System.out.println("jdbcTemplate is null? " + (jdbcTemplate == null)); 

} 

或使用Spring註解:

@Autowired 
@Override 
public void setDataSource(@Qualifier("dataSourceAccounts") DataSource dataSource) 
+0

仍呈現「無匹配的豆例外」 – Ayodeji 2013-02-16 07:59:39

+0

@Ayodeji可能是因爲您的數據源中的XML配置名稱是:「dataSourceProducts」而你指定的「dataSourceAccounts」,「數據源」被注入。 – almalki 2013-02-16 09:29:56

+0

我改變了它,但它仍然不起作用 – Ayodeji 2013-02-16 14:18:56

0

這應該工作

@javax.annotation.Resource(name="dataSourceProducts") 
public void setDataSource(DataSource dataSource) { 
       ... 
} 

javax.annotation.Resource is in Java SE

+0

它顯示了另一個錯誤說「沒有定義命名爲‘dataSourceProducts’豆」即使我有它在XML文件中定義 – Ayodeji 2013-02-16 07:58:17