一、写本博文的原因

年初刚加入到现在的项目时,在使用注解时我用的@Resource。后来,同事:你怎么使用@Resource注解?我:使用它有错吗?同事:没错,但是现在都使用@Autowired。我:我研究一下。

在大学,学习J2EE实训时一直使用的是@Resource注解,后来我就养成习惯了。现在对这两个注解做一下解释:

  • @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

  1. package testwebapp.com.wangzuojia.service;
  2. public interface Human {
  3. public void speak();
  4. public void walk();
  5. }

实现类ManImpl

  1. package testwebapp.com.wangzuojia.service.impl;
  2. import org.springframework.stereotype.Service;
  3. import testwebapp.com.wangzuojia.service.Human;
  4. @Service
  5. public class ManImpl implements Human {
  6. public void speak() {
  7. System.out.println(" man speaking!");
  8. }
  9. public void walk() {
  10. System.out.println(" man walking!");
  11. }
  12. }

实现类WomanImpl

  1. package testwebapp.com.wangzuojia.service.impl;
  2. import org.springframework.stereotype.Service;
  3. import testwebapp.com.wangzuojia.service.Human;
  4. @Service
  5. public class WomanImpl implements Human {
  6. public void speak() {
  7. System.out.println(" woman speaking!");
  8. }
  9. public void walk() {
  10. System.out.println(" woman walking!");
  11. }
  12. }

主调类SequenceServiceImpl

  1. package testwebapp.com.wangzuojia.service.impl;
  2. import java.util.Map;
  3. import javax.annotation.Resource;
  4. import org.springframework.stereotype.Service;
  5. import testwebapp.com.wangzuojia.dao.SequenceMapper;
  6. import testwebapp.com.wangzuojia.service.Human;
  7. import testwebapp.com.wangzuojia.service.SequenceService;
  8. @Service
  9. public class SequenceServiceImpl implements SequenceService {
  10. @Resource
  11. private SequenceMapper sequenceMapper;
  12. public void generateId(Map<String, String> map) {
  13. sequenceMapper.generateId(map);
  14. }
  15. //起服务此处会报错
  16. @Resource
  17. private Human human;
  18. }

这时候启动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有两个实现类。解决方案如下:

  1. package testwebapp.com.wangzuojia.service.impl;
  2. import java.util.Map;
  3. import javax.annotation.Resource;
  4. import org.springframework.stereotype.Service;
  5. import testwebapp.com.wangzuojia.dao.SequenceMapper;
  6. import testwebapp.com.wangzuojia.service.Human;
  7. import testwebapp.com.wangzuojia.service.SequenceService;
  8. @Service
  9. public class SequenceServiceImpl implements SequenceService {
  10. @Resource
  11. private SequenceMapper sequenceMapper;
  12. public void generateId(Map<String, String> map) {
  13. sequenceMapper.generateId(map);
  14. }
  15. @Resource(name = "manImpl")//注意是manImpl不是ManImpl,因为使用@Service,容器为我们创建bean时默认类名首字母小写
  16. private Human human;
  17. }

这样启动服务就不会报错了。如果是使用的@Autowired注解,要配上@Qualifier("manImpl"),代码如下:

    1. package testwebapp.com.wangzuojia.service.impl;
    2. import java.util.Map;
    3. import javax.annotation.Resource;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.beans.factory.annotation.Qualifier;
    6. import org.springframework.stereotype.Service;
    7. import testwebapp.com.wangzuojia.dao.SequenceMapper;
    8. import testwebapp.com.wangzuojia.service.Human;
    9. import testwebapp.com.wangzuojia.service.SequenceService;
    10. @Service
    11. public class SequenceServiceImpl implements SequenceService {
    12. @Resource
    13. private SequenceMapper sequenceMapper;
    14. public void generateId(Map<String, String> map) {
    15. sequenceMapper.generateId(map);
    16. }
    17. @Autowired
    18. @Qualifier("manImpl")
    19. private Human human;
    20. }

@Resource与@Autowired注解的区别的更多相关文章

  1. @Resource与@Autowired注解的区别(转)

    Spring不但支持自己定义的@Autowired注解,还支持由JSR-250规范定义的几个注解.如:@Resource.@PostConstruct及@PreDestroy 1.@Autowired ...

  2. @Resource与@Autowired注解的区别踩坑者入

    一.写本博文的原因 有些童鞋搞不为什么要用@Resource或者@Autowired,咱们一起研究下 @Resource默认按照名称方式进行bean匹配,@Autowired默认按照类型方式进行bea ...

  3. @Resource、@Autowired跟default-autowire区别联系

    @Resource.@Autowired和default-autowire区别联系 今天看了一工程,里面既有default-autowire,又有@Autowired,还有@Resource.我就不明 ...

  4. @Resource、@Autowired、@Qualifier 区别(表格显示)

    @Resource.@Autowired.@Qualifier 区别(表格显示) 区别项 @Resource @Autowired @Qualifier 谁提供的 jdk提供,包是javax.anno ...

  5. @Resource 和 @Autowired注解的异同

    @Resource 和 @Autowired注解的异同 @Autowired 默认按类型装配,默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false 例 ...

  6. spring @Resource与@Autowired注解详解

    具有依赖关系的Bean对象,利用下面任意一种注解都可以实现关系注入: 1)@Resource (默认首先按名称匹配注入,然后类型匹配注入) 2)@Autowired/@Qualifier (默认按类型 ...

  7. @Resource 与 @Service注解的区别

    pring中什么时候用@Resource,什么时候用@service当你需要定义某个类为一个bean,则在这个类的类名前一行使用@Service("XXX"),就相当于讲这个类定义 ...

  8. spring 框架的 @Autowired 和 @Resource 两种注解的区别

    最开始做项目时,依赖注入用到的注解都是 J2EE 的 @Resource,那时还根本不了解 spring 有 @Autowired.心塞. 前两天想到估计有很多刚开始学习 java 的童鞋可能对这两个 ...

  9. Spring @Resource、@Autowired、@Qualifier区别

    @Resource默认是按照名称来装配注入的,只有当找不到与名称匹配的bean才会按照类型来装配注入: @Autowired默认是按照类型装配注入的,如果想按照名称来转配注入,则需要结合@Qualif ...

随机推荐

  1. 20145104张家明 《Java程序设计》第10周学习总结

    20145104张家明 <Java程序设计>第10周学习总结 教材学习内容总结 网络编程 网络编程就是两个或多个设备(程序)之间的数据交换. 识别网络上的每个设备:①IP地址②域名(Dom ...

  2. 20145206邹京儒《网络对抗技术》 PC平台逆向破解

    20145206邹京儒<网络对抗技术> PC平台逆向破解 注入shellcode并执行 一.准备一段shellcode 二.设置环境 具体在终端中输入如下: apt-cache searc ...

  3. 20145327 《网络对抗》Web安全基础实践

    20145327 <网络对抗>Web安全基础实践 实践过程 webgoat开启 java -jar webgoat-container-7.0.1-war-exec.jar 在浏览器输入l ...

  4. 20145336张子扬 《网络对抗技术》 PC平台逆向破解

    #20145336张子扬 <网络对抗技术> PC平台逆向破解 ##Shellcode注入 **基础知识** Shellcode实际是一段代码,但却作为数据发送给受攻击服务器,将代码存储到对 ...

  5. [luoguP1119]灾后重建

    题目链接 毒瘤题 卡spfa 可能dij也卡,没试过 然后放floyd过了 但其实spfa很好打,虽然只有60 让我们来分析一下spfa的效率,假设这个出题人极其毒瘤,出网格图 又因为是在线询问,所以 ...

  6. [JVM] - 继10进制的java.lang.Object查看之后

    cmd清除命令:cls 之后查阅了其它博客,发现这位大神同样也在做JVM,并且我很希望用它的10进制转16进制类来测试一下该解析的10进制是否对应着Object的16进制呢? 这位大神的10进制转16 ...

  7. 【TCP/IP详解 卷一:协议】第十二章 广播和多播

    建议参考:广播和多播 IGMP 12.1 引言 IP地址知识点回顾: IP地址分为三种:(1)单播地址 (2)广播地址 (3)多播地址 另外一种是,IP地址一般划分成五类:A-E类. 单播 考虑 类似 ...

  8. 非[无]root权限 服务器 下安装perl以及perl模块

    转载自http://www.zilhua.com 在本博客中,所有的软件安装都在服务器上,且无root权限.理论上适合所有的用户. 我的安装目录 cd /home/zilhua/software 1. ...

  9. Intel微处理器学习笔记(一) 实模式内存结构

    图一 奔腾概念示意图 存储系统一般划分为三个主要部分:TPA(transient program area),System Area和XMS(extended memory system). 图二 内 ...

  10. Python中通过csv的writerow输出的内容有多余的空行

    第一种方法 如下生成的csv文件会有多个空行 import csv #python2可以用file替代open with open("test.csv","w" ...