@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


package testwebapp.com.wangzuojia.service;
 
public interface Human {
    
    public void speak();
    
    public void walk();
}

实现类ManImpl
package testwebapp.com.wangzuojia.service.impl;
 
import org.springframework.stereotype.Service;
 
import testwebapp.com.wangzuojia.service.Human;
 
@Service
public class ManImpl implements Human {
 
    public void speak() {
        System.out.println(" man speaking!");
 
    }
 
    public void walk() {
        System.out.println(" man walking!");
 
    }
 
}


实现类WomanImpl

package testwebapp.com.wangzuojia.service.impl;
 
import org.springframework.stereotype.Service;
 
import testwebapp.com.wangzuojia.service.Human;
 
@Service
public class WomanImpl implements Human {
 
    public void speak() {
        System.out.println(" woman speaking!");
 
    }
 
    public void walk() {
        System.out.println(" woman walking!");
 
    }
 
}


主调类SequenceServiceImpl

package testwebapp.com.wangzuojia.service.impl;
 
import java.util.Map;
 
import javax.annotation.Resource;
 
import org.springframework.stereotype.Service;
 
import testwebapp.com.wangzuojia.dao.SequenceMapper;
import testwebapp.com.wangzuojia.service.Human;
import testwebapp.com.wangzuojia.service.SequenceService;
 
@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有两个实现类。解决方案如下:

package testwebapp.com.wangzuojia.service.impl;
 
import java.util.Map;
 
import javax.annotation.Resource;
 
import org.springframework.stereotype.Service;
 
import testwebapp.com.wangzuojia.dao.SequenceMapper;
import testwebapp.com.wangzuojia.service.Human;
import testwebapp.com.wangzuojia.service.SequenceService;
 
@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"),代码如下:

package testwebapp.com.wangzuojia.service.impl;
 
import java.util.Map;
 
import javax.annotation.Resource;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
 
import testwebapp.com.wangzuojia.dao.SequenceMapper;
import testwebapp.com.wangzuojia.service.Human;
import testwebapp.com.wangzuojia.service.SequenceService;
 
@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;
 
}

--------------------- 
转载于:https://blog.csdn.net/wangzuojia001/article/details/54312074?utm_source=copy 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: @Resource注解是Java中的一种注解,它可以用来标记一个属性、方法或构造函数,告诉容器在进行自动装配时,使用名称或类型来查找需要注入的bean。 @Autowired注解是Spring框架中的一种注解,它可以用来标记一个属性、方法或构造函数,告诉容器在进行自动装配时,使用类型来查找需要注入的bean。 ### 回答2: @resource注解和@Autowired注解都是用于在Spring框架中进行依赖注入的方式。 @resource注解是JSR 250规范中的一部分,它可以用来标记一个类的属性或方法来指示Spring容器注入一个特定的资源。可以应用在字段上,在setter方法上,以及在构造函数中,用来注入具体类型的依赖。它可以使用一个name属性来指定要注入的资源的名称,如果没有指定name属性,它将根据变量的名称来查找匹配的资源。@resource注解可以用于注入任何类型的资源,包括其他对象、数据源、事务管理器等。 @Autowired注解是Spring框架提供的一种依赖注入方式。它可以通过类型来自动注入一个合适的bean或者其他的依赖项。可以应用在字段上,setter方法上,以及构造函数中。与@resource注解不同的是,@Autowired注解不需要明确指定需要注入的bean的名称,它会根据类型来自动寻找匹配的bean,并将其注入到对应的属性中。如果存在多个相同类型的bean,可以使用@Qualifier注解来指定要注入的bean的名称。在进行注入时,Spring会根据属性的类型,从容器中查找匹配的bean,并将其自动装配到指定的属性中。 总结来说,@resource注解主要用于注入各种类型的资源,可以指定资源的名称,而@Autowired注解主要用于自动注入其他对象或者依赖项,根据类型自动寻找匹配的bean进行注入。 ### 回答3: @Resource注解和@Autowired注解都是Spring框架中用于进行依赖注入的注解。 @Resource注解是JavaEE的注解,可以用于引用其他组件或者资源。在Spring中,它可以用于注入依赖的组件。@Resource注解有两个常用的属性:name和type。name属性可以指定要注入的组件的名称,type属性可以指定要注入的组件的类型。如果两个属性都没有指定,则根据属性的类型进行自动装配。 @Autowired注解是Spring框架提供的注解,用于进行自动装配。它可以根据属性的类型进行自动装配,也可以根据属性的名称进行自动装配。当需要装配的组件只有一个时,会根据类型进行匹配。当需要装配的组件有多个时,会根据属性名称进行匹配。如果找不到匹配的组件,会抛出异常。 在使用@Resource注解时,可以使用@Resource和@Autowired注解的效果是一样的,但是@Resource注解的功能更加强大,可以引用其他JavaEE容器的资源,而@Autowired注解只能引用Spring容器中的组件。 总结起来,@Resource注解是JavaEE的注解,用于引用其他组件或资源,而@Autowired是Spring框架的注解,用于进行自动装配。在Spring中,可以使用@Resource和@Autowired注解来实现依赖注入的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值