自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Java Spring各種依賴注入注解的區(qū)別

開發(fā) 前端
如果使用@Autowired、@Inject或者@Resource注解的時(shí)候,則稍微復(fù)雜一些,會有一個(gè)失敗退化過程,并且引入了Qualifier。不過基本原理是一樣。

[[164298]]

Spring對于Bean的依賴注入,支持多種注解方式:

 

  1. @Resource 
  2. javax.annotation 
  3. JSR250 (Common Annotations for Java) 
  4.  
  5. @Inject 
  6. javax.inject 
  7. JSR330 (Dependency Injection for Java) 
  8.  
  9. @Autowired 
  10. org.springframework.bean.factory 
  11. Spring 

直觀上看起來,@Autowired是Spring提供的注解,其他幾個(gè)都是JDK本身內(nèi)建的注解,Spring對這些注解也進(jìn)行了支持。但是使用起來這三者到底有什么區(qū)別呢?筆者經(jīng)過方法的測試,發(fā)現(xiàn)一些有意思的特性。

區(qū)別總結(jié)如下:

一、@Autowired有個(gè)required屬性,可以配置為false,這種情況下如果沒有找到對應(yīng)的bean是不會拋異常的。@Inject和@Resource沒有提供對應(yīng)的配置,所以必須找到否則會拋異常。

二、 @Autowired和@Inject基本是一樣的,因?yàn)閮烧叨际鞘褂肁utowiredAnnotationBeanPostProcessor來處理 依賴注入。但是@Resource是個(gè)例外,它使用的是CommonAnnotationBeanPostProcessor來處理依賴注入。當(dāng)然,兩者 都是BeanPostProcessor。

 

  1. @Autowired@Inject 
  2. - 默認(rèn) autowired by type 
  3. - 可以 通過@Qualifier 顯式指定 autowired by qualifier name。 
  4. - 如果 autowired by type 失?。ㄕ也坏交蛘哒业蕉鄠€(gè)實(shí)現(xiàn)),則退化為autowired by field name 
  5.  
  6. @Resource 
  7. - 默認(rèn) autowired by field name 
  8. - 如果 autowired by field name失敗,會退化為 autowired by type 
  9. - 可以 通過@Qualifier 顯式指定 autowired by qualifier name 
  10. - 如果 autowired by qualifier name失敗,會退化為 autowired by field name。但是這時(shí)候如果 autowired by field name失敗,就不會再退化為autowired by type了。 

TIPS Qualified name VS Bean name

在Spring設(shè)計(jì)中,Qualified name并不等同于Bean name,后者必須是***的,但是前者類似于tag或者group的作用,對特定的bean進(jìn)行分類??梢赃_(dá)到getByTag(group)的效果。對 于XML配置的bean,可以通過id屬性指定bean name(如果沒有指定,默認(rèn)使用類名首字母小寫),通過標(biāo)簽指定qualifier name:

  1. <bean id="lamborghini" class="me.arganzheng.study.spring.autowired.Lamborghini"
  2.     <qualifier value="luxury"/> 
  3.     <!-- inject any dependencies required by this bean --> 
  4. </bean> 

如果是通過注解方式,那么可以通過@Qualifier注解指定qualifier name,通過@Named或者@Component(@Service,@Repository等)的value值指定bean name:

 

  1. @Component("lamborghini"
  2. @Qualifier("luxury"
  3. public class Lamborghini implements Car { 

或者

 

  1. @Component 
  2. @Named("lamborghini"
  3. @Qualifier("luxury"
  4. public class Lamborghini implements Car { 

同樣,如果沒有指定bean name,那么Spring會默認(rèn)是用類名首字母小寫(Lamborghini=>lamborghini)。

三、 通過Anotation注入依賴的方式在XML注入方式之前進(jìn)行。如果對同一個(gè)bean的依賴同時(shí)使用了兩種注入方式,那么XML的優(yōu)先。但是不同擔(dān)心通過Anotation注入的依賴沒法注入XML中配置的bean,依賴注入是在bean的注冊之后進(jìn)行的。

四、目前的autowired by type方式(筆者用的是3.2.3.RELEASE版本),Spring的AutowiredAnnotationBeanPostProcessor 實(shí)現(xiàn)都是有”bug”的,也就是說@Autowired和@Inject都是有坑的(稱之為坑,不稱之為bug是因?yàn)槊菜剖枪室獾摹?。)。這是來源于線上 的一個(gè)bug,也是這邊文章的寫作原因?,F(xiàn)場如下:

application-context.xml中有如下定義:

 

  1. <xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 
  4.     xmlns:context="http://www.springframework.org/schema/context" 
  5.     xmlns:util="http://www.springframework.org/schema/util" 
  6.     xsi:schemaLocation=" 
  7.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
  8.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
  9.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 
  10.         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd"> 
  11.  
  12.     <context:annotation-config /> 
  13.  
  14.     <context:component-scan base-package="me.arganzheng.study" /> 
  15.  
  16.     <util:constant id="en" 
  17.         static-field="me.arganzheng.study.spring.autowired.Constants.Language.EN" /> 
  18.     <util:constant id="ja" 
  19.         static-field="me.arganzheng.study.spring.autowired.Constants.Language.JP" /> 
  20.     <util:constant id="ind" 
  21.         static-field="me.arganzheng.study.spring.autowired.Constants.Language.IND" /> 
  22.     <util:constant id="pt" 
  23.         static-field="me.arganzheng.study.spring.autowired.Constants.Language.PT" /> 
  24.     <util:constant id="th" 
  25.         static-field="me.arganzheng.study.spring.autowired.Constants.Language.TH" /> 
  26.     <util:constant id="ar" 
  27.         static-field="me.arganzheng.study.spring.autowired.Constants.Language.AR" /> 
  28.     <util:constant id="en-rIn" 
  29.         static-field="me.arganzheng.study.spring.autowired.Constants.Language.EN_RIN" /> 
  30.  
  31.     <util:map id="languageChangesMap" key-type="java.lang.String" 
  32.         value-type="java.lang.String"
  33.         <entry key="pt" value="pt" /> 
  34.         <entry key="br" value="pt" /> 
  35.         <entry key="jp" value="ja" /> 
  36.         <entry key="ja" value="ja" /> 
  37.         <entry key="ind" value="ind" /> 
  38.         <entry key="id" value="ind" /> 
  39.         <entry key="en-rin" value="en-rIn" /> 
  40.         <entry key="in" value="en-rIn" /> 
  41.         <entry key="en" value="en" /> 
  42.         <entry key="gb" value="en" /> 
  43.         <entry key="th" value="th" /> 
  44.         <entry key="ar" value="ar" /> 
  45.         <entry key="eg" value="ar" /> 
  46.     </util:map> 
  47.  
  48. </beans> 

其中static-field應(yīng)用的常量定義在如下類中:

 

  1. package me.arganzheng.study.spring.autowired; 
  2.  
  3. public interface Constants { 
  4.  
  5.     public interface Language { 
  6.         public static final String EN = "CommonConstants.LANG_ENGLISH"
  7.         public static final String JP = "CommonConstants.LANG_JAPANESE"
  8.         public static final String IND = "CommonConstants.LANG_INDONESIAN"
  9.         public static final String PT = "CommonConstants.LANG_PORTUGUESE"
  10.         public static final String TH = "CommonConstants.LANG_THAI"
  11.         public static final String EN_RIN = "CommonConstants.LANG_ENGLISH_INDIA"
  12.         public static final String AR = "CommonConstants.LANG_Arabic"
  13.     } 

然后如果我們在代碼中如下聲明依賴:

 

  1. public class AutowiredTest extends BaseSpringTestCase { 
  2.  
  3.     @Autowired 
  4.     private Map<String, String> languageChangesMap; 
  5.  
  6.     @Test 
  7.     public void testAutowired() { 
  8.         notNull(languageChangesMap); 
  9.         System.out.println(languageChangesMap.getClass().getSimpleName()); 
  10.         System.out.println(languageChangesMap); 
  11.     } 

Guess what,詭異的事情發(fā)生了!

運(yùn)行結(jié)果如下:

  1. LinkedHashMap 
  2. {en=CommonConstants.LANG_ENGLISH, ja=CommonConstants.LANG_JAPANESE, ind=CommonConstants.LANG_INDONESIAN, pt=CommonConstants.LANG_PORTUGUESE, th=CommonConstants.LANG_THAI, ar=CommonConstants.LANG_Arabic, en-rIn=CommonConstants.LANG_ENGLISH_INDIA} 

也就是說Map

  1. 嚴(yán)重: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@5c51ee0a] to prepare test instance [me.arganzheng.study.spring.autowired.AutowiredTest@6e301e0
  2. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'me.arganzheng.study.spring.autowired.AutowiredTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.Map me.arganzheng.study.spring.autowired.AutowiredTest.languageChangesMap; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency [map with value type java.lang.String]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
  1. ... 
  2. ed by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency [map with value type java.lang.String]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
  3. at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986
  4. at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:843
  5. at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768
  6. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486
  7. ... 28 more 

debug了一下,發(fā)現(xiàn)確實(shí)是Spring的一個(gè)bug。在DefaultListableBeanFactory的這個(gè)方法出問題了:

 

  1. protected Object doResolveDependency(DependencyDescriptor descriptor, Class<?> type, String beanName, 
  2.             Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException { 
  3.         ...     
  4.  
  5.         else if (Map.class.isAssignableFrom(type) && type.isInterface()) { 
  6.             Class<?> keyType = descriptor.getMapKeyType(); 
  7.             if (keyType == null || !String.class.isAssignableFrom(keyType)) { 
  8.                 if (descriptor.isRequired()) { 
  9.                     throw new FatalBeanException("Key type [" + keyType + "] of map [" + type.getName() + 
  10.                             "] must be assignable to [java.lang.String]"); 
  11.                 } 
  12.                 return null
  13.             } 
  14.             Class<?> valueType = descriptor.getMapValueType(); 
  15.             if (valueType == null) { 
  16.                 if (descriptor.isRequired()) { 
  17.                     throw new FatalBeanException("No value type declared for map [" + type.getName() + "]"); 
  18.                 } 
  19.                 return null
  20.             } 
  21.             Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, descriptor); 
  22.             if (matchingBeans.isEmpty()) { 
  23.                 if (descriptor.isRequired()) { 
  24.                     raiseNoSuchBeanDefinitionException(valueType, "map with value type " + valueType.getName(), descriptor); 
  25.                 } 
  26.                 return null
  27.             } 
  28.             if (autowiredBeanNames != null) { 
  29.                 autowiredBeanNames.addAll(matchingBeans.keySet()); 
  30.             } 
  31.             return matchingBeans; 
  32.         } 
  33.         ... 
  34.     } 

關(guān)鍵在這一句:Map

  1. 嚴(yán)重: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@9476189] to prepare test instance [me.arganzheng.study.spring.autowired.AutowiredTest@2d546e21
  2. ... 
  3. Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency [map with value type java.lang.String]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=languageChangesMap)} 
  4.     at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986
  5.     at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:843
  6.     at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768
  7.     at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486
  8.     ... 28 more 

debug了一下,發(fā)現(xiàn)跟沒有指定qualifie name是一樣的執(zhí)行路徑。不是指定了bean name了嗎?為什么還是autowired by type呢?仔細(xì)查看了一下才發(fā)現(xiàn)。DefaultListableBeanFactory的doResolveDependency方法對首先對類型做 了區(qū)別:

 

  1. protected Object doResolveDependency(DependencyDescriptor descriptor, Class<?> type, String beanName, 
  2.             Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException { 
  3.  
  4.         Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); 
  5.         if (value != null) { 
  6.             if (value instanceof String) { 
  7.                 String strVal = resolveEmbeddedValue((String) value); 
  8.                 BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null); 
  9.                 value = evaluateBeanDefinitionString(strVal, bd); 
  10.             } 
  11.             TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); 
  12.             return (descriptor.getField() != null ? 
  13.                     converter.convertIfNecessary(value, type, descriptor.getField()) : 
  14.                     converter.convertIfNecessary(value, type, descriptor.getMethodParameter())); 
  15.         } 
  16.  
  17.         if (type.isArray()) { 
  18.             Class<?> componentType = type.getComponentType(); 
  19.             Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); 
  20.             if (matchingBeans.isEmpty()) { 
  21.                 if (descriptor.isRequired()) { 
  22.                     raiseNoSuchBeanDefinitionException(componentType, "array of " + componentType.getName(), descriptor); 
  23.                 } 
  24.                 return null
  25.             } 
  26.             if (autowiredBeanNames != null) { 
  27.                 autowiredBeanNames.addAll(matchingBeans.keySet()); 
  28.             } 
  29.             TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); 
  30.             return converter.convertIfNecessary(matchingBeans.values(), type); 
  31.         } 
  32.         else if (Collection.class.isAssignableFrom(type) && type.isInterface()) { 
  33.             Class<?> elementType = descriptor.getCollectionType(); 
  34.             if (elementType == null) { 
  35.                 if (descriptor.isRequired()) { 
  36.                     throw new FatalBeanException("No element type declared for collection [" + type.getName() + "]"); 
  37.                 } 
  38.                 return null
  39.             } 
  40.             Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType, descriptor); 
  41.             if (matchingBeans.isEmpty()) { 
  42.                 if (descriptor.isRequired()) { 
  43.                     raiseNoSuchBeanDefinitionException(elementType, "collection of " + elementType.getName(), descriptor); 
  44.                 } 
  45.                 return null
  46.             } 
  47.             if (autowiredBeanNames != null) { 
  48.                 autowiredBeanNames.addAll(matchingBeans.keySet()); 
  49.             } 
  50.             TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); 
  51.             return converter.convertIfNecessary(matchingBeans.values(), type); 
  52.         } 
  53.         else if (Map.class.isAssignableFrom(type) && type.isInterface()) { 
  54.             Class<?> keyType = descriptor.getMapKeyType(); 
  55.             if (keyType == null || !String.class.isAssignableFrom(keyType)) { 
  56.                 if (descriptor.isRequired()) { 
  57.                     throw new FatalBeanException("Key type [" + keyType + "] of map [" + type.getName() + 
  58.                             "] must be assignable to [java.lang.String]"); 
  59.                 } 
  60.                 return null
  61.             } 
  62.             Class<?> valueType = descriptor.getMapValueType(); 
  63.             if (valueType == null) { 
  64.                 if (descriptor.isRequired()) { 
  65.                     throw new FatalBeanException("No value type declared for map [" + type.getName() + "]"); 
  66.                 } 
  67.                 return null
  68.             } 
  69.             Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, descriptor); 
  70.             if (matchingBeans.isEmpty()) { 
  71.                 if (descriptor.isRequired()) { 
  72.                     raiseNoSuchBeanDefinitionException(valueType, "map with value type " + valueType.getName(), descriptor); 
  73.                 } 
  74.                 return null
  75.             } 
  76.             if (autowiredBeanNames != null) { 
  77.                 autowiredBeanNames.addAll(matchingBeans.keySet()); 
  78.             } 
  79.             return matchingBeans; 
  80.         } 
  81.         else { 
  82.             Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); 
  83.             if (matchingBeans.isEmpty()) { 
  84.                 if (descriptor.isRequired()) { 
  85.                     raiseNoSuchBeanDefinitionException(type, "", descriptor); 
  86.                 } 
  87.                 return null
  88.             } 
  89.             if (matchingBeans.size() > 1) { 
  90.                 String primaryBeanName = determinePrimaryCandidate(matchingBeans, descriptor); 
  91.                 if (primaryBeanName == null) { 
  92.                     throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet()); 
  93.                 } 
  94.                 if (autowiredBeanNames != null) { 
  95.                     autowiredBeanNames.add(primaryBeanName); 
  96.                 } 
  97.                 return matchingBeans.get(primaryBeanName); 
  98.             } 
  99.             // We have exactly one match. 
  100.             Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next(); 
  101.             if (autowiredBeanNames != null) { 
  102.                 autowiredBeanNames.add(entry.getKey()); 
  103.             } 
  104.             return entry.getValue(); 
  105.         } 
  106.     } 

如果是Array,Collection或者M(jìn)ap,則根據(jù)集合類中元素的類型來進(jìn)行autowired by type(Map使用value的類型)。為什么這么特殊處理呢?原來,Spring是為了達(dá)到這樣的目的:讓你可以一次注入所有符合類型的實(shí)現(xiàn),也就是 說可以這樣子注入:

  1. @Autowired 
  2. private List<Car> cars; 

如果你的car有多個(gè)實(shí)現(xiàn),那么都會注入進(jìn)來,不會再報(bào)

 

  1. org.springframework.beans.factory.NoSuchBeanDefinitionException: 
  2. No unique bean of type [me.arganzheng.study.spring.autowired.Car] is defined: 
  3. expected single matching bean but found 2: [audi, toyota]. 
  4.  
  5. 然而,上面的情況如果你用@Resource則不會有這個(gè)問題: 
  6.  
  7. public class AutowiredTest extends BaseSpringTestCase { 
  8.  
  9.     @Resource 
  10.     @Qualifier("languageChangesMap"
  11.     private Map<String, String> languageChangesMap; 
  12.  
  13.     @Test 
  14.     public void testAutowired() { 
  15.         assertNotNull(languageChangesMap); 
  16.         System.out.println(languageChangesMap.getClass().getSimpleName()); 
  17.         System.out.println(languageChangesMap); 
  18.     } 

正常運(yùn)行:

  1. LinkedHashMap 
  2. {pt=pt, br=pt, jp=ja, ja=ja, ind=ind, id=ind, en-rin=en-rIn, in=en-rIn, en=en, gb=en, th=th, ar=ar, eg=ar} 

當(dāng)然,你如果不指定@Qualifier(“languageChangesMap”),同時(shí)field name不是languageChangesMap,那么還是一樣報(bào)錯的。

 

  1. Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency [map with value type java.lang.String]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, mappedName=, description=, name=, type=class java.lang.Object, authenticationType=CONTAINER, lookup=)} 
  2. at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986
  3. at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:843
  4. at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768
  5. at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:438
  6. at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:416
  7. at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:550
  8. at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150
  9. at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87
  10. at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:303
  11. ... 26 more 

而且,@Resource也可以實(shí)現(xiàn)上面的List接收所有實(shí)現(xiàn):

 

  1. public class AutowiredTest extends BaseSpringTestCase { 
  2.  
  3.     @Resource 
  4.     @Qualifier("languageChangesMap"
  5.     private Map<String, String> languageChangesMap; 
  6.  
  7.     @Resource 
  8.     private List<Car> cars; 
  9.  
  10.     @Test 
  11.     public void testAutowired() { 
  12.         assertNotNull(languageChangesMap); 
  13.         System.out.println(languageChangesMap.getClass().getSimpleName()); 
  14.         System.out.println(languageChangesMap); 
  15.  
  16.         assertNotNull(cars); 
  17.         System.out.println(cars.getClass().getSimpleName()); 
  18.         System.out.println(cars); 
  19.     } 

運(yùn)行的妥妥的:

  1. LinkedHashMap 
  2. {pt=pt, br=pt, jp=ja, ja=ja, ind=ind, id=ind, en-rin=en-rIn, in=en-rIn, en=en, gb=en, th=th, ar=ar, eg=ar} 
  3. ArrayList 
  4. [me.arganzheng.study.spring.autowired.Audi@579584da, me.arganzheng.study.spring.autowired.Toyota@19453122

這是因?yàn)锧Resource注解使用的是CommonAnnotationBeanPostProcessor處理器,跟 AutowiredAnnotationBeanPostProcessor不是同一個(gè)作者[/偷笑]。這里就不分析了,感興趣的同學(xué)可以自己看代碼研究 一下。

最終結(jié)論如下:

1、@Autowired和@Inject

autowired by type 可以 通過@Qualifier 顯式指定 autowired by qualifier name(非集合類。注意:不是autowired by bean name?。?br /> 如果 autowired by type 失?。ㄕ也坏交蛘哒业蕉鄠€(gè)實(shí)現(xiàn)),則退化為autowired by field name(非集合類)

2、@Resource

默認(rèn) autowired by field name
如果 autowired by field name失敗,會退化為 autowired by type
可以 通過@Qualifier 顯式指定 autowired by qualifier name
如果 autowired by qualifier name失敗,會退化為 autowired by field name。但是這時(shí)候如果 autowired by field name失敗,就不會再退化為autowired by type了

測試工程保存在GitHub上,是標(biāo)準(zhǔn)的maven工程,感興趣的同學(xué)可以clone到本地運(yùn)行測試一下。

補(bǔ)充

有同事指出Spring官方文檔上有這么一句話跟我的結(jié)有點(diǎn)沖突:

However, although you can use this convention to refer to specific beans by name, @Autowired is fundamentally about type-driven injection with optional semantic qualifiers. This means that qualifier values, even with the bean name fallback, always have narrowing semantics within the set of type matches; they do not semantically express a reference to a unique bean id.

也就是說@Autowired即使加了@Qualifier注解,其實(shí)也是autowired by type。@Qualifier只是一個(gè)限定詞,過濾條件而已。重新跟進(jìn)了一下代碼,發(fā)現(xiàn)確實(shí)是這樣子的。Spring設(shè)計(jì)的這個(gè) @Qualifier name 并不等同于 bean name。他有點(diǎn)類似于一個(gè)tag。不過如果這個(gè)tag是***的化,那么其實(shí)效果上等同于bean name。實(shí)現(xiàn)上,Spring是先getByType,得到list candicates,然后再根據(jù)qualifier name進(jìn)行過濾。

再定義一個(gè)蘭博基尼,這里使用@Qualifier指定:

 

  1. package me.arganzheng.study.spring.autowired; 
  2.  
  3. import org.springframework.beans.factory.annotation.Qualifier; 
  4. import org.springframework.stereotype.Component; 
  5.  
  6. @Component 
  7. @Qualifier("luxury"
  8. public class Lamborghini implements Car { 
  9.  

再定義一個(gè)勞斯萊斯,這里故意用@Named指定:

 

  1. package me.arganzheng.study.spring.autowired; 
  2.  
  3. import javax.inject.Named; 
  4.  
  5. import org.springframework.stereotype.Component; 
  6.  
  7. @Component 
  8. @Named("luxury"
  9. public class RollsRoyce implements Car { 
  10.  

測試一下注入定義的豪華車:

 

  1. package me.arganzheng.study.spring.autowired; 
  2.  
  3. import static junit.framework.Assert.assertNotNull; 
  4.  
  5. import java.util.List; 
  6.  
  7. import me.arganzheng.study.BaseSpringTestCase; 
  8.  
  9. import org.junit.Test; 
  10. import org.springframework.beans.factory.annotation.Autowired; 
  11. import org.springframework.beans.factory.annotation.Qualifier; 
  12.  
  13. /** 
  14. * 
  15. * @author zhengzhibin 
  16. * 
  17. */ 
  18. public class AutowiredTest extends BaseSpringTestCase { 
  19.  
  20.     @Autowired 
  21.     @Qualifier("luxury"
  22.     private List<Car> luxuryCars; 
  23.  
  24.     @Test 
  25.     public void testAutowired() { 
  26.  
  27.         assertNotNull(luxuryCars); 
  28.         System.out.println(luxuryCars.getClass().getSimpleName()); 
  29.         System.out.println(luxuryCars); 
  30.     } 
  31.  

運(yùn)行結(jié)果如下:

  1. ArrayList 
  2. [me.arganzheng.study.spring.autowired.Lamborghini@66b875e1, me.arganzheng.study.spring.autowired.RollsRoyce@58433b76

補(bǔ)充:Autowiring modes

Spring支持四種autowire模式,當(dāng)使用XML配置方式時(shí),你可以通過autowire屬性指定。

  1. no. (Default) No autowiring. Bean references must be defined via a ref element. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system. 
  2. byName. Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. For example, if a bean definition is set to autowire by name, and it contains a master property (that is, it has a setMaster(..) method), Spring looks for a bean definition named master, and uses it to set the property. 
  3. byType. Allows a property to be autowired if exactly one bean of the property type exists in the container. If more than one exists, a fatal exception is thrown, which indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens; the property is not set. 
  4. constructor. Analogous to byType, but applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised. 

如果使用@Autowired、@Inject或者@Resource注解的時(shí)候,則稍微復(fù)雜一些,會有一個(gè)失敗退化過程,并且引入了Qualifier。不過基本原理是一樣。

責(zé)任編輯:王雪燕 來源: 徐劉根
相關(guān)推薦

2011-05-31 10:00:21

Android Spring 依賴注入

2023-07-11 09:14:12

Beanquarkus

2011-04-15 09:44:45

Spring

2009-06-15 17:48:32

Spring注解注入屬性

2022-04-30 08:50:11

控制反轉(zhuǎn)Spring依賴注入

2009-09-08 15:22:20

Spring依賴注入

2020-08-06 00:14:16

Spring IoC依賴注入開發(fā)

2011-03-01 13:45:41

Spring3Annotation

2022-12-29 08:54:53

依賴注入JavaScript

2023-10-07 08:35:07

依賴注入Spring

2021-07-29 06:55:03

Spring@AutowriedbyType注入

2015-09-02 11:22:36

JavaScript實(shí)現(xiàn)思路

2024-08-26 08:52:41

2023-09-14 08:16:50

Lazy注解null

2021-12-15 09:17:12

Spring依賴注入面試題

2022-08-24 07:06:36

SpringSetter項(xiàng)目

2024-05-27 00:13:27

Go語言框架

2009-05-21 16:41:22

GuiceJava依賴注入

2016-01-05 10:35:04

JavaSpringJavaConfig

2012-12-25 10:53:09

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號