@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.AbstractBeanFactory1.getObject(AbstractBeanFactory.java:306)&nbsp;atorg.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)&nbsp;atorg.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)&nbsp;atorg.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)&nbsp;atorg.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)&nbsp;atorg.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838)&nbsp;atorg.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)&nbsp;atorg.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)&nbsp;atorg.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)&nbsp;atorg.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)&nbsp;atorg.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4717)&nbsp;atorg.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)atorg.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)&nbsp;atorg.apache.catalina.core.ContainerBase 1.getObject(AbstractBeanFactory.java:306)&nbsp;atorg.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)&nbsp;atorg.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)&nbsp;atorg.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)&nbsp;atorg.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)&nbsp;atorg.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838)&nbsp;atorg.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)&nbsp;atorg.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)&nbsp;atorg.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)&nbsp;atorg.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)&nbsp;atorg.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4717)&nbsp;atorg.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)atorg.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)&nbsp;atorg.apache.catalina.core.ContainerBase StartChild.call(ContainerBase.java:1404) atorg.apache.catalina.core.ContainerBaseStartChild.call(ContainerBase.java:1394)&nbsp;atjava.util.concurrent.FutureTask.run(FutureTask.java:266)&nbsp;atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)&nbsp;atjava.util.concurrent.ThreadPoolExecutor StartChild.call(ContainerBase.java:1394)&nbsp;atjava.util.concurrent.FutureTask.run(FutureTask.java:266)&nbsp;atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)&nbsp;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.CommonAnnotationBeanPostProcessorResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:615)&nbsp;atorg.springframework.beans.factory.annotation.InjectionMetadata ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:615)&nbsp;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. }



            </div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值