我试图从我的context.xml文件中注入一个数据源。我有这个配置文件,但问题是,我随时都有多个数据源。当我尝试注入其中任何一个时,我得到一个错误,表示没有匹配的bean。 这是我的代码。
@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>
感谢您提前帮助。
答案 0 :(得分:2)
如果要为应该注入的依赖项指定限定名,@ Named应该在param定义之前:
@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)
答案 1 :(得分:0)
这应该有效
@javax.annotation.Resource(name="dataSourceProducts")
public void setDataSource(DataSource dataSource) {
...
}
javax.annotation.Resource在Java SE中