在开发里程兑换接口的过程中,我将一个在文件夹com.csair.baggage下的@component的bean,换到了com.csair.baggage.ratio,然后在启动后,tomcat localhost log下就报了如下错误。
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'mileageRatioClient' for bean class [com.csair.baggage.ratio.MileageRatioClient] conflicts with existing, non-compatible bean definition of same name and class [com.csair.baggage.MileageRatioClient]
原因:Spring容器里已经有一个来自com.csair.baggage包的id为MileageRatioClient。现在现在通过@Component标注,com.csair.baggage.ratio下也有一个MileageRatioClient的bean,因此造成了定义冲突。为何com.csair.baggage下已经没有MileageRatioClient了,还会有这个bean呢,应该是Spring还没刷新,依然存了改动之前的bean。
原理:在配置文件content.xml中<context:component-scan base package="com.csair.baggage"></context:component-scan>设置了扫描路径,因此启动时,Spring扫描到com.csair.baggage.ratio下的MileageRatioClient,就会创建id为MileageRatioClient的Bean。
方法:可以在标签@Component中指定新的bean的id。@Component("MileageRatioClients") 这样就可以与之前的那个区别开。
然后在使用的时候,
@Autowired
@Qualifier(value ="MileageRatioClients")
或者
@Resource(name="MileageRatioClients")
通知Spring去找id为MileageRatioClients的bean就不会有冲突了。