在项目中开发用到注入有时用@Resource,有时用@Autowired,但到底两者有什么区别呢?
1、匹配方式
@Resource默认是按照名称方式进行bean匹配
@Autowired默认按照类型方式进行bean匹配
2、所属包
@Resource(javax.annotation.Resource)
@Autowired(org.springframework.beans.factory.annotation.Autowired)
3、测试场景
一个接口HumanService、两个实现类WomanServiceImpl、ManServiceImpl,在service层的一个bean中引用接口Human
HumanService接口
实现类1:WomanServiceImpl
实现类2:ManServiceImpl
调用类方式一:使用@Autowired
报错:需要一个唯一的注入bean,但是发现了两个
Field humanService in com.ice.springboot.diveinspringboot.controller.People required a single bean, but 2 were found:
- manServiceImpl: defined in file [/Users/allin/InteliJ3/dive-in-spring-boot/target/classes/com/ice/springboot/diveinspringboot/serviceimpl/ManServiceImpl.class]
- womanServiceImpl: defined in file [/Users/allin/InteliJ3/dive-in-spring-boot/target/classes/com/ice/springboot/diveinspringboot/serviceimpl/WomanServiceImpl.class]
Action:
Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
- womanServiceImpl: defined in file [/Users/allin/InteliJ3/dive-in-spring-boot/target/classes/com/ice/springboot/diveinspringboot/serviceimpl/WomanServiceImpl.class]
解决办法:
1、在其中一个bean上添加@Primary
2、在注入的时候,添加@Qualifier声明那个是要注入的bean
调用类方式一:使用@Resource 会有类似的报错
解决办法:@Resource(name = “manServiceImpl”)指定实现类即可,注意用小写的首字母,因为容器创建bean时默认首字母小写
参考:https://blog.csdn.net/wangzuojia001/article/details/54312074/