@Resource与@Autowired注解的区别

一、写本博文的原因

年初刚加入到现在的项目时,在使用注解时我用的@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

[java] view plain copy

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

实现类ManImpl

[java] view plain copy

  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

[java] view plain copy

  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

[java] view plain copy

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

[java] view plain copy

  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"),代码如下:

[java] view plain copy

    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. }

原文地址:https://www.cnblogs.com/yuluoxingkong/p/8805270.html

时间: 2024-07-31 18:04:21

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

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

最开始做项目时,依赖注入用到的注解都是 J2EE 的 @Resource,那时还根本不了解 spring 有 @Autowired.心塞. 前两天想到估计有很多刚开始学习 java 的童鞋可能对这两个注解并没有注意区分,那我就在这总结一下吧.当然很多都是 copy 自网络. 相同点: 1. 都是用来装配 Bean,都可以写在字段上,或者写在 setter 方法上. 不同点: @Autowired 1. 默认按类型装配. 2. 默认情况下必须要求对象存在,如果允许 Null 值,可是设置 requ

@Resource 和 @Autowired注解的异同

@Autowired 默认按类型装配,默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false 例如: @Autowired(required=false),如果我们想使用名称装配可以结合@Qualifier注解进行使用 @Controller @RequestMapping("user") public class LoginController{ @Autowired @Qualifier("loginService"

Spring Resource、Autowired、Qualifier的注解注入及区别

 说明和区别 spring4.1 提供了基于注解(Annotation-based)的配置,我们可以通过注解的方式来完成注入依赖.在Java代码中可以使用 @Resource或者@Autowired注解方式来经行注入.虽然@Resource和@Autowired都可以来完成注入依赖,但它们之间是有区 别的.首先来看一下: a.@Resource默认是按照名称来装配注入的,只有当找不到与名称匹配的bean才会按照类型来装配注入: b.@Autowired默认是按照类型装配注入的,如果想按照名称

Spring @Resource、@Autowired、@Qualifier的注解注入及区别

spring2.5提供了基于注解(Annotation-based)的配置,我们可以通过注解的方式来完成注入依赖.在Java代码中可以使用 @Resource或者@Autowired注解方式来经行注入.虽然@Resource和@Autowired都可以来完成注入依赖,但它们之间是有区别的.首先来看一下: @Resource默认是按照名称来装配注入的,只有当找不到与名称匹配的bean才会按照类型来装配注入: @Autowired默认是按照类型装配注入的,如果想按照名称来转配注入,则需要结合@Qua

@Resource、@Autowired、@Qualifier的注解注入及区别

在Java代码中可以使用 @Resource  或者 @Autowired 注解方式来进行注入. 虽然 @Resource 和 @Autowried 都可以完成依赖注入,但是他们是有区别的. 一: @Resource 默认是按照名称来装配注入的,只有当找不到与名称匹配的bean才会按照类型来注入. 它有两个属性是比较重要的: ①. name: Spring 将 name 的属性值解析为 bean 的名称, 使用 byName 的自动注入策略 ②. type: Spring 将 type的属性值解

Spring5:@Autowired注解、@Resource注解和@Service注解

什么是注解 传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事物,这么做有两个缺点: 1.如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大:如果按需求分开.xml文件,那么.xml文件又会非常多.总之这将导致配置文件的可读性与可维护性变得很低 2.在开发中在.java文件和.xml文件之间不断切换,是一件麻烦的事,同时这种思维上的不连贯也会降低开发的效率 为了解决这两个问题,Spring引入了注解,通过"@XXX"的方式,让注解与Java

Spring中@Autowired注解、@Resource注解的区别(转)

标签: Autowired Resource Spring(3)  Spring不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource.@PostConstruct以及@PreDestroy. @Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按 byName自动注入罢了.@Resource有两个属性是比较重要的,分是name和type,Spring将@Reso

Spring注解@Resource和@Autowired区别

一.相同点: @Autowired和@Resource作用基本相同,都是用于自动装配bean对象.都可以写在字段上,或写在setter方法上. 二.不同点: 1.出处不同 @Autowired(Spring注解,org.springframework.beans.factory.annotation.Autowired) @Resource(JAVA注解,javax.annotation.Resource).适用范围广,依赖小. 2.自动装配策略不同 @Resource 默认优先名称匹配, 具体

Spring中@Autowired注解、@Resource注解的区别

Spring不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource.@PostConstruct以及@PreDestroy. @Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按 byName自动注入罢了.@Resource有两个属性是比较重要的,分是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析