注释指定的Bean名称与现有的不兼容Bean定义冲突 [英] Annotation-specified bean name conflicts with existing, non-compatible bean def

查看:1456
本文介绍了注释指定的Bean名称与现有的不兼容Bean定义冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对某些Spring bean定义有疑问.我的main()方法正在加载几个上下文xml文件,并且它们几乎都包含一个标记.当我的主要方法启动时,我从Spring得到这个错误:

I'm having a problem with some Spring bean definitions. I have a couple of context xml files that are being loaded by my main() method, and both of them contain almost exclusively a tag. When my main method starts up, I get this error from Spring:

Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'converterDAO' for bean class [my.package.InMemoryConverterDaoImpl] conflicts with existing, non-compatible bean definition of same name and class [my.other.package.StaticConverterDAOImpl]

两个DAO类都以这种方式注释:

Both DAO classes are annotated this way:

@Repository("converterDAO")
public class StaticConverterDAOImpl implements ConverterDAO {
...
}

内存中的dao也具有@Repository("converterDAO")批注. dao在其他类似这样的类中被引用:

The in-memory dao also has the @Repository("converterDAO") annotation. The dao is referenced in other classes like this:

...
private @Autowired @Qualifier("converterDAO") ConverterDAO converterDAO;
...

我希望一个DAO覆盖另一个DAO的定义,据我所知,这是首先使用DI框架的主要原因之一.多年来,我一直在使用xml定义进行此操作,并且从未遇到任何问题.但是组件扫描和带注释的Bean定义不是这样吗?当Spring说它们不兼容"时,这意味着什么?它们实现相同的接口,并且自动连接到该接口类型的字段中.为什么它们不兼容?

I want one DAO to override the definition of the other one, which as I always understood it was one of the principal reasons to use a DI framework in the first place. I've been doing this with xml definitions for years and never had any problems. But not so with component scans and annotated bean definitions? And what does Spring mean when it says they are not "compatible"? They implement the same interface, and they are autowired into fields that are of that interface type. Why the heck are they not compatible?

有人可以为我提供一种方法,让一个带注释的,经过组件扫描的bean覆盖另一个吗?

Can someone provide me with a way for one annotated, component-scanned bean to override another?

-迈克

推荐答案

在XML文件中,有一系列声明,您可以用较新的定义覆盖先前的定义.使用批注时,没有之前之后的概念.所有的豆都处于同一水平.您定义了两个具有相同名称的bean,而Spring不知道应该选择哪个.

In an XML file, there is a sequence of declarations, and you may override a previous definition with a newer one. When you use annotations, there is no notion of before or after. All the beans are at the same level. You defined two beans with the same name, and Spring doesn't know which one it should choose.

给他们一个不同的名字(例如 staticConverterDAO ,例如 inMemoryConverterDAO ),在Spring XML文件中创建一个别名(例如 theConverterDAO ) ,并在注入转换器时使用以下别名:

Give them a different name (staticConverterDAO, inMemoryConverterDAO for example), create an alias in the Spring XML file (theConverterDAO for example), and use this alias when injecting the converter:

@Autowired @Qualifier("theConverterDAO")

这篇关于注释指定的Bean名称与现有的不兼容Bean定义冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆