【发布时间】:2013-09-06 10:37:52
【问题描述】:
我在创建两个相同类但限定符名称不同的 bean 时遇到问题。基本上,一个 bean 是使用 @Repository 注释创建的,另一个是在 @Configuration 类中创建的。
这是我们不会使用不同数据源的两个实例的类:
@Repository ("someDao")
public class SomeDaoImpl implements SomeDao {
private NamedParameterJdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
}
然后我们有这样的服务:
@Service
public class SomeServiceImpl implements
SomeService {
@Resource(name = "someDao")
private SomeDao someDao;
@Resource(name = "someDaoAnotherDataSource")
private SomeDao someDaoAnotherDataSource;
}
我的第一个 bean 是由注释 @Repository 创建的,另一个是我在 Spring Configuration 类中声明的:
@Configuration
@ComponentScan(basePackages = "mypackages")
public abstract class ApplicationRootConfiguration {
@Bean(name = "otherDataSource")
public DataSource otherDataSource() throws NamingException {
...
}
@Bean(name = "someDaoAnotherDataSource")
public SomeDao getSomeDaoAnotherDataSource(@Qualifier("otherDataSource")
DataSource dataSource) throws NamingException {
SomeDao dao = new SomeDaoImpl();
dao.setDataSource(dataSource);
return dao;
}
}
如果我运行我的应用程序,SomeServiceImpl 中的属性 someDaoAnotherDataSource 没有在配置类中声明我的 bean,它使用注释存储库声明了 bean。
另外,如果我在 XML 配置中运行相同的示例,它可以工作:
<bean id="someDaoAnotherDataSource" class="SomeDaoImpl">
<property name="dataSource" ref="otherDataSource" />
</bean>
知道为什么不自动装配正确的 bean 吗?
提前致谢。
【问题讨论】:
-
这对我有用。你确定名字是正确的吗?
-
是的,它似乎必须工作,因为它几乎相同,但没有。你用的是什么春季版本?我正在使用 3.2.4.RELEASE。
-
对我来说也一样。把它分解成最简单的形式,然后再试一次。
-
你能发布你的完整配置吗?或者至少是模仿它的东西?您发布的 xml sn-p 以与
@Configuration注释 bean 相同的方式(和某些上下文)加载?
标签: java spring ioc-container