1. 程式人生 > >【轉】@Resource與@Autowired註解的區別

【轉】@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;
 
}