我有基于Spring的Web项目的代码:
控制器:
@Controller
@RequestMapping("mycontroller")
public class MyObjectController {
@Autowired
private MyService service;
// Code omitted
}
服务
@Service
public class MyServiceImpl implements MyService {
@Autowired
@Qualifier("mydao")
private MyDao mydao;
@Autowired
@Qualifier("mydao2")
private MyDao2 mydao2;
// Code omitted
}
Context.xml(Spring):
<annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.mycompany" />
<beans:bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<beans:bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<beans:bean id="myService" class="com.mycompany.serviceimpl.MyServiceImpl" />
然而它会抛出此错误:
NoSuchBeanDefinitionException:没有定义[com.mycompany.service.MyService]类型的唯一bean:期望的单个匹配bean但找到2:[myService,myServiceImpl]
答案 0 :(得分:4)
您的bean 定义了两次,此处(@Service
注释导致注册myServiceImpl
bean):
@Service
public class MyServiceImpl implements MyService {
和此处(在Context.xml
中,带有myService
id的bean):
<beans:bean id="myService" class="com.mycompany.serviceimpl.MyServiceImpl" />
从XML中删除定义或删除注释。
答案 1 :(得分:1)
您 将@Service
放在MyServiceImpl
上,或您在Context.xml
中声明了该bean。不要两者都做,否则你最终会得到两个豆子。
从XML文件中删除myService
bean定义,你应该好好去。
此外,您不需要声明DefaultAnnotationHandlerMapping
或AnnotationMethodHandlerAdapter
bean - 默认情况下可以使用这些bean。