@Resource与@Autowired注解的区别踩坑者入
一、写本博文的原因
有些童鞋搞不为什么要用@Resource或者@Autowired,咱们一起研究下
@Resource默认按照名称方式进行bean匹配,@Autowired默认按照类型方式进行bean匹配
@Resource(import javax.annotation.Resource;)是J2EE的注解,@Autowired( import org.springframework.beans.factory.annotation.Autowired;)是Spring的注解
Spring属于第三方的,J2EE是Java自己的东西。使用@Resource可以减少代码和Spring之间的耦合。
二、@Resource注入
现在有一个接口Human和两个实现类ManImpl、WomanImpl,在service层的一个bean中要引用了接口Human,这种情况处理如下:
接口Human
- public interface Human {public void speak();public void walk();}
实现类ManImpl
@Service
public class ManImpl implements Human {
public void speak() {
System.out.println(" man speaking!");
}
public void walk() {
System.out.println(" man walking!");
}
}
实现类WomanImp
@Service
public class WomanImpl implements Human {
public void speak() {
System.out.println(" woman speaking!");
}
public void walk() {
System.out.println(" woman walking!");
}
}
主调类SequenceServiceImpl
@Service
public class SequenceServiceImpl implements SequenceService {
@Resource
private SequenceMapper sequenceMapper;
public void generateId(Map<String, String> map) {
sequenceMapper.generateId(map);
}
//起服务此处会报错
@Resource
private Human human;
}
这时候启动tomcat会包如下错误:
严重: Exception sendingcontext initialized event to listener instance of classorg.springframework.web.context.ContextLoaderListenerorg.springframework.beans.factory.BeanCreationException: Error creating beanwith name 'sequenceServiceImpl': Injection of resource dependencies failed;nested exception isorg.springframework.beans.factory.NoUniqueBeanDefinitionException: Noqualifying bean of type [testwebapp.com.wangzuojia.service.Human] is defined:expected single matching beanbut found 2: manImpl,womanImpl atorg.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:311) atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) atorg.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) atorg.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) atorg.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) atorg.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) atorg.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) atorg.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838) atorg.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) atorg.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446) atorg.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328) atorg.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) atorg.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4717) atorg.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)atorg.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) atorg.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1404) atorg.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1394) atjava.util.concurrent.FutureTask.run(FutureTask.java:266) atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) atjava.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)atjava.lang.Thread.run(Thread.java:745) Caused by:org.springframework.beans.factory.NoUniqueBeanDefinitionException: Noqualifying bean of type [testwebapp.com.wangzuojia.service.Human] is defined: expectedsingle matching bean but found 2: manImpl,womanImpl atorg.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1126) atorg.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) atorg.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:508) atorg.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:486) atorg.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:615) atorg.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169) atorg.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) atorg.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:308) ...22 more
报错的地方给我们提示了:but found 2: manImpl,womanImpl 意思是Human有两个实现类。解决方案如下:
@Service
public class SequenceServiceImpl implements SequenceService {
@Resource
private SequenceMapper sequenceMapper;
public void generateId(Map<String, String> map) {
sequenceMapper.generateId(map);
}
@Resource(name = "manImpl")//注意是manImpl不是ManImpl,因为使用@Service,容器为我们创建bean时默认类名首字母小写
private Human human;
}
这样启动服务就不会报错了。如果是使用的@Autowired注解,要配上@Qualifier("manImpl"),代码如下:
@Service
public class SequenceServiceImpl implements SequenceService {
@Resource
private SequenceMapper sequenceMapper;
public void generateId(Map<String, String> map) {
sequenceMapper.generateId(map);
}
@Autowired
@Qualifier("manImpl")
private Human human;
}
希望对你有帮助,欢迎交流+QQ3245792286
最新文章
- 【图像处理】【SEED-VPM】4.串口调试信息
- .net 下判断中英文字符串长度
- 【大数据】Summingbird(Storm + Hadoop)的demo运行
- html 中几次方,平方米,立方米,下标,上标,删除线等的表示方法
- CentOS6.5菜鸟之旅:关于搜索的shell命令
- hdu5878 I Count Two Three(二分+ 打表)
- CSS绝对定位和相对定位 position: absolute/relative
- 大四实习准备3_java多线程
- 【转】 Linux内核中读写文件数据的方法--不错
- Linux APP源码级编译安装
- 标准Http协议的六种请求方法详解
- tensorflow-mnist报错[WinError 10060] 由于连接方在一段时间后没有正确答复解决办法
- [JAVA] TicTacToe实现Socket通信(一)
- git常用命令总结——你一定会用到的几个命令
- Oracle 数据库导出数据泵(EXPDP)文件存放的位置
- HDU 1115(求质量均匀分布的多边形重心 物理)
- 基于bootstrap的后台左侧导航菜单和点击二级菜单刷新二级页面时候菜单展开显示当前菜单
- robotium测试创建java文件和junit文件区别
- Aviator 表达式求值引擎开源框架
- python单链表
热门文章
- 精讲JS逻辑运算符&;&;、||,位运算符|,&;
- Java - 单链表
- OGG 从Oracle备库同步数据至kafka
- Jdbc中大文本类型的处理
- 在本地局域网 windows server 2008 下安装 Nginx 1.12.1
- [nginx]设置代理和静态资源目录
- python 学习笔记(二):为元组的每个元素命名,提高程序的可读性
- Linux0.11之进程0创建进程1(1)
- 从gopath到go mod的一次尝试
- 从内存上看python的对象