Annotation injection, as the name suggests, is to achieve injection through annotations. Common annotations related to Spring and injection include Autowired, Resource, Qualifier, Service, Controller, Repository, and Component.
Autowired is automatic injection, automatically finding the appropriate bean from the spring context to inject
Resource is used to specify the name for injection
Qualifier cooperates with Autowired Use, specify the name of the bean
Service, Controller, and Repository to mark the classes as Service layer classes, Controller layer classes, and data storage layer classes. When spring scans the annotation configuration, it will mark these classes to generate beans.
Component is a general term that marks classes as components. When spring scans the annotation configuration, it will mark these classes to generate beans.
Spring supports multiple annotation methods for Bean dependency injection:
@Resource javax.annotation JSR250 (Common Annotations for Java) @Inject javax.inject JSR330 (Dependency Injection for Java) @Autowired org.springframework.bean.factory Spring
Intuitively, @Autowired is an annotation provided by Spring, and the others are Spring also supports the built-in annotations of the JDK itself. But what is the difference between these three in use? After testing the method, the author found some interesting features.
The differences are summarized as follows:
1. @Autowired has a required attribute, which can be configured as false. In this case, if the corresponding bean is not found, an exception will not be thrown. @Inject and @Resource do not provide corresponding configuration, so they must be found otherwise an exception will be thrown.
2. @Autowired and @Inject are basically the same, because both use AutowiredAnnotationBeanPostProcessor to handle dependency injection. But @Resource is an exception, it uses CommonAnnotationBeanPostProcessor to handle dependency injection. Of course, both are BeanPostProcessors.
@Autowired和@Inject - 默认 autowired by type - 可以 通过@Qualifier 显式指定 autowired by qualifier name。 - 如果 autowired by type 失败(找不到或者找到多个实现),则退化为autowired by field name @Resource - 默认 autowired by field name - 如果 autowired by field name失败,会退化为 autowired by type - 可以 通过@Qualifier 显式指定 autowired by qualifier name - 如果 autowired by qualifier name失败,会退化为 autowired by field name。但是这时候如果 autowired by field name失败,就不会再退化为autowired by type了。
TIPS Qualified name VS Bean name
In Spring design, Qualified name is not equivalent to Bean name. The latter must be unique, but the former is similar to The role of tag or group is to classify specific beans. The effect of getByTag(group) can be achieved. For XML configured beans, you can specify the bean name through the id attribute (if not specified, the first letter of the class name is lowercase by default), and specify the qualifier name through the label:
<bean id="lamborghini" class="me.arganzheng.study.spring.autowired.Lamborghini"> <qualifier value="luxury"/> <!-- inject any dependencies required by this bean --> </bean>
If it is through annotation method, then you can specify the qualifier name through the @Qualifier annotation, and specify the bean name through the value of @Named or @Component (@Service, @Repository, etc.):
@Component("lamborghini") @Qualifier("luxury") public class Lamborghini implements Car { }
or
@Component @Named("lamborghini") @Qualifier("luxury") public class Lamborghini implements Car { }
Similarly, if the bean name is not specified, Spring will default to lowercase the first letter of the class name (Lamborghini=>lamborghini).
3. Inject dependencies through Anotation before XML injection. If both injection methods are used for a dependency on the same bean, the XML one takes precedence. However, there is no need to worry that dependencies injected through Anotation cannot be injected into beans configured in XML. Dependency injection is performed after the bean is registered.
4. The current autowired by type method (the author is using the 3.2.3.RELEASE version), Spring's AutowiredAnnotationBeanPostProcessor implementation all have "bugs", that is to say, both @Autowired and @Inject have "bugs" It's a bug (it's called a bug, not a bug because it seems to be intentional...). This is a bug from online, and it is also the reason for writing this article. The scene is as follows:
application-context.xml has the following definition:
<xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd"> <context:annotation-config /> <context:component-scan base-package="me.arganzheng.study" /> <util:constant id="en" static-field="me.arganzheng.study.spring.autowired.Constants.Language.EN" /> <util:constant id="ja" static-field="me.arganzheng.study.spring.autowired.Constants.Language.JP" /> <util:constant id="ind" static-field="me.arganzheng.study.spring.autowired.Constants.Language.IND" /> <util:constant id="pt" static-field="me.arganzheng.study.spring.autowired.Constants.Language.PT" /> <util:constant id="th" static-field="me.arganzheng.study.spring.autowired.Constants.Language.TH" /> <util:constant id="ar" static-field="me.arganzheng.study.spring.autowired.Constants.Language.AR" /> <util:constant id="en-rIn" static-field="me.arganzheng.study.spring.autowired.Constants.Language.EN_RIN" /> <util:map id="languageChangesMap" key-type="java.lang.String" value-type="java.lang.String"> <entry key="pt" value="pt" /> <entry key="br" value="pt" /> <entry key="jp" value="ja" /> <entry key="ja" value="ja" /> <entry key="ind" value="ind" /> <entry key="id" value="ind" /> <entry key="en-rin" value="en-rIn" /> <entry key="in" value="en-rIn" /> <entry key="en" value="en" /> <entry key="gb" value="en" /> <entry key="th" value="th" /> <entry key="ar" value="ar" /> <entry key="eg" value="ar" /> </util:map> </beans>
The constants applied by static-field are defined in the following class:
package me.arganzheng.study.spring.autowired; public interface Constants { public interface Language { public static final String EN = "CommonConstants.LANG_ENGLISH"; public static final String JP = "CommonConstants.LANG_JAPANESE"; public static final String IND = "CommonConstants.LANG_INDONESIAN"; public static final String PT = "CommonConstants.LANG_PORTUGUESE"; public static final String TH = "CommonConstants.LANG_THAI"; public static final String EN_RIN = "CommonConstants.LANG_ENGLISH_INDIA"; public static final String AR = "CommonConstants.LANG_Arabic"; } }
Then if we declare the dependency as follows in the code:
public class AutowiredTest extends BaseSpringTestCase { @Autowired private Map<String, String> languageChangesMap; @Test public void testAutowired() { notNull(languageChangesMap); System.out.println(languageChangesMap.getClass().getSimpleName()); System.out.println(languageChangesMap); } }
Guess what, something weird happened!
The running results are as follows:
LinkedHashMap {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}
That is to say Map
Serious: Caught exception while allowing TestExecutionListener
[org.springframework.test.context.support.DependencyInjectionTestExecutionListener@5c51ee0a] to prepare test instance [me.arganzheng.study.spring.autowired.AutowiredTest@6e301e0] 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)} ... 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)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:843) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486) ... 28 more
Debugged it and found that it was indeed a Spring bug. There is a problem with this method in DefaultListableBeanFactory:
protected Object doResolveDependency(DependencyDescriptor descriptor, Class<?> type, String beanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException { ... else if (Map.class.isAssignableFrom(type) && type.isInterface()) { Class<?> keyType = descriptor.getMapKeyType(); if (keyType == null || !String.class.isAssignableFrom(keyType)) { if (descriptor.isRequired()) { throw new FatalBeanException("Key type [" + keyType + "] of map [" + type.getName() + "] must be assignable to [java.lang.String]"); } return null; } Class<?> valueType = descriptor.getMapValueType(); if (valueType == null) { if (descriptor.isRequired()) { throw new FatalBeanException("No value type declared for map [" + type.getName() + "]"); } return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, descriptor); if (matchingBeans.isEmpty()) { if (descriptor.isRequired()) { raiseNoSuchBeanDefinitionException(valueType, "map with value type " + valueType.getName(), descriptor); } return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } return matchingBeans; } ... }
The key is this sentence: Map
Severe: Caught exception while allowing TestExecutionListener
[org.springframework.test.context.support.DependencyInjectionTestExecutionListener@9476189] to prepare test instance [me.arganzheng.study.spring.autowired.AutowiredTest@2d546e21] ... 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)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:843) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486) ... 28 more
After debugging, I found that the execution path is the same as if the qualifie name was not specified. Isn't the bean name specified? Why is it still autowired by type? After a closer look, I discovered it. The doResolveDependency method of DefaultListableBeanFactory first distinguishes the types:
protected Object doResolveDependency(DependencyDescriptor descriptor, Class<?> type, String beanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); if (value != null) { if (value instanceof String) { String strVal = resolveEmbeddedValue((String) value); BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null); value = evaluateBeanDefinitionString(strVal, bd); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); return (descriptor.getField() != null ? converter.convertIfNecessary(value, type, descriptor.getField()) : converter.convertIfNecessary(value, type, descriptor.getMethodParameter())); } if (type.isArray()) { Class<?> componentType = type.getComponentType(); Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); if (matchingBeans.isEmpty()) { if (descriptor.isRequired()) { raiseNoSuchBeanDefinitionException(componentType, "array of " + componentType.getName(), descriptor); } return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); return converter.convertIfNecessary(matchingBeans.values(), type); } else if (Collection.class.isAssignableFrom(type) && type.isInterface()) { Class<?> elementType = descriptor.getCollectionType(); if (elementType == null) { if (descriptor.isRequired()) { throw new FatalBeanException("No element type declared for collection [" + type.getName() + "]"); } return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType, descriptor); if (matchingBeans.isEmpty()) { if (descriptor.isRequired()) { raiseNoSuchBeanDefinitionException(elementType, "collection of " + elementType.getName(), descriptor); } return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); return converter.convertIfNecessary(matchingBeans.values(), type); } else if (Map.class.isAssignableFrom(type) && type.isInterface()) { Class<?> keyType = descriptor.getMapKeyType(); if (keyType == null || !String.class.isAssignableFrom(keyType)) { if (descriptor.isRequired()) { throw new FatalBeanException("Key type [" + keyType + "] of map [" + type.getName() + "] must be assignable to [java.lang.String]"); } return null; } Class<?> valueType = descriptor.getMapValueType(); if (valueType == null) { if (descriptor.isRequired()) { throw new FatalBeanException("No value type declared for map [" + type.getName() + "]"); } return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, descriptor); if (matchingBeans.isEmpty()) { if (descriptor.isRequired()) { raiseNoSuchBeanDefinitionException(valueType, "map with value type " + valueType.getName(), descriptor); } return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } return matchingBeans; } else { Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); if (matchingBeans.isEmpty()) { if (descriptor.isRequired()) { raiseNoSuchBeanDefinitionException(type, "", descriptor); } return null; } if (matchingBeans.size() > 1) { String primaryBeanName = determinePrimaryCandidate(matchingBeans, descriptor); if (primaryBeanName == null) { throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet()); } if (autowiredBeanNames != null) { autowiredBeanNames.add(primaryBeanName); } return matchingBeans.get(primaryBeanName); } // We have exactly one match. Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next(); if (autowiredBeanNames != null) { autowiredBeanNames.add(entry.getKey()); } return entry.getValue(); } }
If it is Array, Collection or Map, it is autowired by type according to the type of elements in the collection class (Map uses value type). Why is it treated so specially? It turns out that Spring is designed to achieve this purpose: allowing you to inject all implementations that match the type at once, which means you can inject it like this:
@Autowired
private List6aae3388faff3c39a78c7dd06b2c35df cars;
If your car has multiple implementations, they will all be injected and will not be reported again
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [me.arganzheng.study.spring.autowired.Car] is defined: expected single matching bean but found 2: [audi, toyota].
However, if you use @Resource in the above situation, you will not have this problem :
public class AutowiredTest extends BaseSpringTestCase { @Resource @Qualifier("languageChangesMap") private Map<String, String> languageChangesMap; @Test public void testAutowired() { assertNotNull(languageChangesMap); System.out.println(languageChangesMap.getClass().getSimpleName()); System.out.println(languageChangesMap); } }
Normal operation:
LinkedHashMap {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}
Of course, if you do not specify @Qualifier("languageChangesMap") and the field name is not languageChangesMap, Then the error is still the same.
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=)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:843) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:438) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:416) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:550) at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:303) ... 26 more
Moreover, @Resource can also implement the above List to receive all implementations:
public class AutowiredTest extends BaseSpringTestCase { @Resource @Qualifier("languageChangesMap") private Map<String, String> languageChangesMap; @Resource private List<Car> cars; @Test public void testAutowired() { assertNotNull(languageChangesMap); System.out.println(languageChangesMap.getClass().getSimpleName()); System.out.println(languageChangesMap); assertNotNull(cars); System.out.println(cars.getClass().getSimpleName()); System.out.println(cars); } }
Running properly:
LinkedHashMap {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} ArrayList
[me.arganzheng.study.spring.autowired.Audi@579584da, me.arganzheng.study.spring.autowired.Toyota@19453122]
这是因为@Resource注解使用的是CommonAnnotationBeanPostProcessor处理器,跟 AutowiredAnnotationBeanPostProcessor不是同一个作者[/偷笑]。这里就不分析了,感兴趣的同学可以自己看代码研究 一下。
最终结论如下:
1、@Autowired和@Inject
autowired by type 可以 通过@Qualifier 显式指定 autowired by qualifier name(非集合类。注意:不是autowired by bean name!)
如果 autowired by type 失败(找不到或者找到多个实现),则退化为autowired by field name(非集合类)
2、@Resource
默认 autowired by field name
如果 autowired by field name失败,会退化为 autowired by type
可以 通过@Qualifier 显式指定 autowired by qualifier name
如果 autowired by qualifier name失败,会退化为 autowired by field name。但是这时候如果 autowired by field name失败,就不会再退化为autowired by type了
测试工程保存在GitHub上,是标准的maven工程,感兴趣的同学可以clone到本地运行测试一下。
补充
有同事指出Spring官方文档上有这么一句话跟我的结有点冲突:
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注解,其实也是autowired by type。@Qualifier只是一个限定词,过滤条件而已。重新跟进了一下代码,发现确实是这样子的。Spring设计的这个 @Qualifier name 并不等同于 bean name。他有点类似于一个tag。不过如果这个tag是唯一的化,那么其实效果上等同于bean name。实现上,Spring是先getByType,得到list candicates,然后再根据qualifier name进行过滤。
再定义一个兰博基尼,这里使用@Qualifier指定:
package me.arganzheng.study.spring.autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component @Qualifier("luxury") public class Lamborghini implements Car { }
再定义一个劳斯莱斯,这里故意用@Named指定:
package me.arganzheng.study.spring.autowired; import javax.inject.Named; import org.springframework.stereotype.Component; @Component @Named("luxury") public class RollsRoyce implements Car { }
测试一下注入定义的豪华车:
package me.arganzheng.study.spring.autowired; import static junit.framework.Assert.assertNotNull; import java.util.List; import me.arganzheng.study.BaseSpringTestCase; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; /** * * @author zhengzhibin * */ public class AutowiredTest extends BaseSpringTestCase { @Autowired @Qualifier("luxury") private List<Car> luxuryCars; @Test public void testAutowired() { assertNotNull(luxuryCars); System.out.println(luxuryCars.getClass().getSimpleName()); System.out.println(luxuryCars); } }
运行结果如下:
ArrayList [me.arganzheng.study.spring.autowired.Lamborghini@66b875e1, me.arganzheng.study.spring.autowired.RollsRoyce@58433b76]
补充:Autowiring modes
Spring支持四种autowire模式,当使用XML配置方式时,你可以通过autowire属性指定。
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. 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. 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. 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注解的时候,则稍微复杂一些,会有一个失败退化过程,并且引入了Qualifier。不过基本原理是一样。
更多详解Java Spring各种依赖注入注解的区别相关文章请关注PHP中文网!