Spring发现多个bean定义错误

时间:2012-05-19 17:08:41

标签: java spring spring-mvc

我有基于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]

2 个答案:

答案 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定义,你应该好好去。

此外,您不需要声明DefaultAnnotationHandlerMappingAnnotationMethodHandlerAdapter bean - 默认情况下可以使用这些bean。