我试图使用Spring for webapp自动连接一些bean(用于依赖注入)。一个控制器bean包含另一个bean,它又保存另一组bean的hashmap。现在地图上只有一个条目。当我在tomcat中运行并调用该服务时,我收到一条错误,指出第二个bean(控制器中保存)不是唯一的
No unique bean of type [com.hp.it.km.search.web.suggestion.SuggestionService] is defined: expected single matching bean but found 2: [suggestionService,SuggestionService]
我无法看到我在哪里定义这个bean两次,但是对于Spring和自动布线来说是新的,所以我可能会缺少一些基本的东西。下面列出的xml和2类的源代码…
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.hp.it.km.search.web.suggestion" /> <mvc:annotation-driven /> <context:annotation-config /> <bean id="SuggestionController" class="com.hp.it.km.search.web.suggestion.SuggestionController"> <property name="service"> <ref bean="SuggestionService" /> </property> </bean> <bean id="SuggestionService" class="com.hp.it.km.search.web.suggestion.SuggestionService"> <property name="indexSearchers"> <map> <entry key="KMSearcher"> <ref bean="KMSearcherBean"></ref></entry> </map> </property> </bean> <bean id="KMSearcherBean" class="com.hp.it.km.search.web.suggestion.SuggestionIndexSearcher"> <constructor-arg index="0" value="KMSearcher" /> <constructor-arg index="1" value="C://dev//workspace//search-restful-webapp//src//main//resources//indexes//keyword" /> </bean>
与自动连线控制器和服务bean的类屁股在这里…
@Controller public class SuggestionController { private SuggestionService service; @Autowired public void setService(SuggestionService service) { this.service = service; } public SuggestionService getService() { return service; }
和…
@Component public class SuggestionService { private Map<String,IndexSearcher> indexSearchers = new HashMap<String,IndexSearcher>(); @Autowired public void setIndexSearchers(Map<String,IndexSearcher> indexSearchers) { this.indexSearchers = indexSearchers; } public SuggestionService() { super(); }
请帮忙!
问题是因为您有一个通过@Component注释创建的SuggestionService类型的bean,也是通过XML配置创建的。如JB Nizet所解释的,这将导致通过@Component创建一个名为“suggestionService”的bean,另一个通过XML创建名为“SuggestionService”的bean。
原文链接:https://www.f2er.com/javaschema/282293.html当您在控制器中引用@Autowired的SuggestionService时,默认情况下,Spring会自动导线“类型”,并找到两个类型为“SuggestionService”的bean
您可以执行以下操作
>从您的服务中删除@Component,并依赖于通过XML映射 – 最简单
>从XML中删除SuggestionService并自动连接依赖关系 – 使用util:map注入indexSearchers映射。
>使用@Resource而不是@Autowired来选择它的名称。
@Resource("suggestionService") private SuggestionService service;
要么
@Resource("SuggestionService") private SuggestionService service;
两者都应该工作。第三个是肮脏的修复,最好通过其他方式解决bean冲突。