Reputation: 35276
I have this code for my Spring-based web project:
Controller:
@Controller
@RequestMapping("mycontroller")
public class MyObjectController {
@Autowired
private MyService service;
// Code omitted
}
Service:
@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" />
However it throws this error:
NoSuchBeanDefinitionException: No unique bean of type [com.mycompany.service.MyService] is defined: expected single matching bean but found 2: [myService, myServiceImpl]
Upvotes: 2
Views: 2412
Reputation: 340708
Your bean is defined twice, here (@Service
annotation, results in registering myServiceImpl
bean):
@Service
public class MyServiceImpl implements MyService {
and here (in Context.xml
, bean with myService
id):
<beans:bean id="myService" class="com.mycompany.serviceimpl.MyServiceImpl" />
Either remove the definition from XML or remove the annotation.
Upvotes: 4
Reputation: 403441
You either put @Service
on MyServiceImpl
, or you declare the bean in Context.xml
. Don't do both, or you'll end up with two beans.
Remove the myService
bean definition from the XML file, and you should be good to go.
Also, you shouldn't need to declare DefaultAnnotationHandlerMapping
or AnnotationMethodHandlerAdapter
beans - those are available by default.
Upvotes: 1