Ⅳ Spring的依赖注入源码解析
- 前言
- 什么是依赖注入
- 依赖注入的方式
- 1.手动注入
- 2.自动注入
- Xml的autowired自动注入
- byName和byType
- contructor
- default和no
- 更细粒度的控制
- XML的自动注入底层
- @Autowired注解自动注入
- @Autowired注解底层
- 依赖注入的流程
- 1.寻找注入点
- 找注入点的流程
- static的字段或方法为什么不支持
- 桥接方法
- 2.注入点进行注入
- 字段注入
- Set方法注入
- 核心方法的实现
- 1.resolveDependency()
- 2.findAutowireCandidates()
- 源码流程
- 源码分析
- 3.依赖注入中泛型注入的实现
- 代码解析
- 处理流程
- 注解讲解
- 1.@Qualifier
- 使用@Autowired自动注入的时候,可以在属性或参数加上@Qualifier("xxx")指定注入到对象:
- 可以作为筛选的限定符,我们在写自定义的注解时,可以在其定义上增加@Qualifier,来筛选需要的对象:
- 2.@Resource
凡事只要一丝不苟就能与众不同
前言
上篇文章有讲到,在Spring启动过程中,执行BeanFactory后置处理器完成扫描并生成最终BeanDefinition后。接下来由该BeanDefinition去创建Bean的过程中,在Bean完成实例化后会进行依赖注入。
什么是依赖注入
DI (Dependency Injection):依赖注入是指在 Spring IOC 容器创建对象的过程中,将所依赖的对象通过配置进行注入。
依赖注入的方式
1.手动注入
手动注入的底层分为两种,Set方法注入以及构造方法注入
通过Xml定义Bean手动给某个属性赋值:
// 底层通过set方法进行注入// 底层通过构造方法进行注入
2.自动注入
自动注入分为两种,Xml的autowire自动注入以及@Autowired注解的自动注入
Xml的autowired自动注入
在XML中,可以在定义一个Bean时去指定这个Bean的自动注入模式:
- byType:通过类型注入
- byName:通过名称注入
- constructor:构造方法注入
- default:默认
- no:无
Spring会自动的给userService中所有的属性自动赋值(不需要这个属性上有@Autowired注解,但需要这个属性有对应的set方法),如:
在创建Bean的过程中,在填充属性时,Spring会去解析当前类,把当前类的所有方法都解析出来,得到每个方法对应的PropertyDescriptor对象,PropertyDescriptor中有几个属性:
- name:这个name并不是方法的名字,而是拿方法名字进过处理后的名字
- 如果方法名字以“get”开头,比如“getXXX”,那么name=XXX
- 如果方法名字以“is”开头,比如“isXXX”,那么name=XXX
- 如果方法名字以“set”开头,比如“setXXX”,那么name=XXX
- readMethodRef:表示get方法的Method对象的引用
- readMethodName:表示get方法的名字
- writeMethodRef:表示set方法的Method对象的引用
- writeMethodName:表示set方法的名字
- propertyTypeRef:如果有get方法那么对应的就是返回值的类型,如果是set方法那么对应的就是set方法中唯一参数的类型
get方法的定义: 方法参数个数为0个,并且 (方法名字以"get"开头 或者 方法名字以"is"开头并且方法的返回类型为boolean)
set方法的定义:方法参数个数为1个,并且 (方法名字以"set"开头并且方法返回类型为void)
byName和byType
byName自动填充属性流程:
- 找到所有set方法所对应的XXX部分的名字
- 根据XXX部分的名字去获取bean
byType自动填充属性流程:
- 获取到set方法中的唯一参数的参数类型,并且根据该类型去容器中获取bean
- 如果找到多个,会报错
contructor
constructor表示通过构造方法注入
当某个bean是通过构造方法来注入时,spring利用构造方法的参数信息从Spring容器中去找bean,找到bean之后作为参数传给构造方法,从而实例化得到一个bean对象,并完成属性赋值(属性赋值的代码得程序员来写)。
这里只考虑只有一个有参构造方法,暂不考虑一个类有多个构造方法的情况,后面单独讲推断构造方法
其实构造方法注入相当于byType+byName,普通的byType是根据set方法中的参数类型去找bean,找到多个会报错,而constructor就是通过构造方法中的参数类型去找bean,如果找到多个会根据参数名确定。
default和no
no:表示关闭autowire
default:表示默认值,我们一直演示的某个bean的autowire,而也可以直接在标签中设置autowire,如果设置了,那么标签中设置的autowire如果为default,那么则会用标签中设置的autowire。
可以发现XML中的自动注入是挺强大的,那么问题来了,为什么我们平时都是用的@Autowired注解呢?而没有用上文说的这种自动注入方式呢?
@Autowired注解相当于XML中的autowire属性的注解方式的替代。这是在官网上有提到的。
Essentially, the @Autowired annotation provides the same capabilities as described in Autowiring Collaborators but with more fine-grained control and wider applicability
从本质上讲,@Autowired注解提供了与autowire相同的功能,但是拥有更细粒度的控制和更广泛的适用性
更细粒度的控制
XML中的autowire控制的是整个bean的所有属性,而@Autowired注解是直接写在某个属性、某个set方法、某个构造方法上的。
再举个例子,如果一个类有多个构造方法,那么如果用XML的autowire=constructor,你无法控制到底用哪个构造方法,而你可以用@Autowired注解来直接指定你想用哪个构造方法。
同时,用@Autowired注解,还可以控制,哪些属性想被自动注入,哪些属性不想,这也是细粒度的控制。
但是@Autowired无法区分byType和byName,@Autowired是先byType,如果找到多个则byName。
XML的自动注入底层
- set方法注入
- 构造方法注入
@Autowired注解自动注入
@Autowired注解,是byType和byName的结合
@Autowired注解可以写在:
- 属性上:先根据属性类型去找Bean,如果找到多个再根据属性名确定一个
- 构造方法上:先根据方法参数类型去找Bean,如果找到多个再根据参数名确定一个
- set方法上:先根据方法参数类型去找Bean,如果找到多个再根据参数名确定一个
@Autowired注解底层
- 属性注入
- set方法注入
- 构造方法注入
依赖注入的流程
1.寻找注入点
在创建一个Bean的过程中,Spring会利用AutowiredAnnotationBeanPostProcessor的postProcessMergedBeanDefinition()找出注入点并缓存
找注入点的流程
- 遍历当前类的所有的属性字段Field
- 查看字段上是否存在@Autowired、@Value、@Inject中的其中任意一个,存在则认为该字段是一个注入点
- 如果字段是static的,则不进行注入
- 获取@Autowired中的required属性的值
- 将字段信息构造成一个AutowiredFieldElement对象,作为一个注入点对象添加到currElements集合中
- 遍历当前类的所有方法Method
- 判断当前Method是否是桥接方法,如果是找到原方法
- 查看方法上是否存在@Autowired、@Value、@Inject中的其中任意一个,存在则认为该方法是一个注入点
- 如果方法是static的,则不进行注入
- 获取@Autowired中的required属性的值
- 将方法信息构造成一个AutowiredMethodElement对象,作为一个注入点对象添加到currElements集合中
- 遍历完当前类的字段和方法后,将遍历父类的,直到没有父类。
- 最后将currElements集合封装成一个InjectionMetadata对象,作为当前Bean对于的注入点集合对象,并缓存
static的字段或方法为什么不支持
@Component @Scope("prototype") public class OrderService { }
@Component @Scope("prototype") public class UserService { @Autowired private static OrderService orderService; public void test() { System.out.println("test123"); } }
看上面代码,UserService和OrderService都是原型Bean,假设Spring支持static字段进行自动注入,那么现在调用两次
- UserService userService1 = context.getBean(“userService”)
- UserService userService2 = context.getBean(“userService”)
问:此时,userService1的orderService值是什么?还是它自己注入的值吗?
答案:不是,一旦userService2 创建好了之后,static orderService字段的值就发生了修改了,从而出现bug。
桥接方法
public interface UserInterface{ void setOrderService(T t); }
@Component public class UserService implements UserInterface{ private OrderService orderService; @Override @Autowired public void setOrderService(OrderService orderService) { this.orderService = orderService; } public void test() { System.out.println("test123"); } }
// class version 52.0 (52) // access flags 0x21 // signature Ljava/lang/Object;Lcom/fish/service/UserInterface; // declaration: com/fish/service/UserService implements com.fish.service.UserInterface public class com/fish/service/UserService implements com/fish/service/UserInterface { // compiled from: UserService.java @Lorg/springframework/stereotype/Component;() // access flags 0x2 private Lcom/fish/service/OrderService; orderService // access flags 0x1 public ()V L0 LINENUMBER 12 L0 ALOAD 0 INVOKESPECIAL java/lang/Object. ()V RETURN L1 LOCALVARIABLE this Lcom/fish/service/UserService; L0 L1 0 MAXSTACK = 1 MAXLOCALS = 1 // access flags 0x1 public setOrderService(Lcom/fish/service/OrderService;)V @Lorg/springframework/beans/factory/annotation/Autowired;() L0 LINENUMBER 19 L0 ALOAD 0 ALOAD 1 PUTFIELD com/fish/service/UserService.orderService : Lcom/fish/service/OrderService; L1 LINENUMBER 20 L1 RETURN L2 LOCALVARIABLE this Lcom/fish/service/UserService; L0 L2 0 LOCALVARIABLE orderService Lcom/fish/service/OrderService; L0 L2 1 MAXSTACK = 2 MAXLOCALS = 2 // access flags 0x1 public test()V L0 LINENUMBER 23 L0 GETSTATIC java/lang/System.out : Ljava/io/PrintStream; LDC "test123" INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V L1 LINENUMBER 24 L1 RETURN L2 LOCALVARIABLE this Lcom/fish/service/UserService; L0 L2 0 MAXSTACK = 2 MAXLOCALS = 1 // access flags 0x1041 public synthetic bridge setOrderService(Ljava/lang/Object;)V @Lorg/springframework/beans/factory/annotation/Autowired;() L0 LINENUMBER 11 L0 ALOAD 0 ALOAD 1 CHECKCAST com/fish/service/OrderService INVOKEVIRTUAL com/fish/service/UserService.setOrderService (Lcom/fish/service/OrderService;)V RETURN L1 LOCALVARIABLE this Lcom/fish/service/UserService; L0 L1 0 MAXSTACK = 2 MAXLOCALS = 2 }
可以看到在UserSerivce的字节码中有两个setOrderService方法:
- public setOrderService(Lcom/fish/service/OrderService;)V
- public synthetic bridge setOrderService(Ljava/lang/Object;)V
并且都是存在@Autowired注解的。
所以在Spring中需要处理这种情况,当遍历到桥接方法时,得找到原方法。
2.注入点进行注入
Spring在AutowiredAnnotationBeanPostProcessor的postProcessProperties()方法中,会遍历所找到的注入点依次进行注入
字段注入
- 遍历所有的AutowiredFieldElement对象。
- 将对应的字段封装为DependencyDescriptor对象。
- 调用BeanFactory的resolveDependency()方法,传入DependencyDescriptor对象,进行依赖查找,找到当前字段所匹配的Bean对象。
- 将DependencyDescriptor对象和所找到的结果对象beanName封装成一个ShortcutDependencyDescriptor对象作为缓存,比如如果当前Bean是原型Bean,那么下次再来创建该Bean时,就可以直接拿缓存的结果对象beanName去BeanFactory中去那bean对象了,不用再次进行查找了
- 利用反射将结果对象赋值给字段。
Set方法注入
- 遍历所有的AutowiredMethodElement对象
- 遍历将对应的方法的参数,将每个参数封装成MethodParameter对象
- 将MethodParameter对象封装为DependencyDescriptor对象
- 调用BeanFactory的resolveDependency()方法,传入DependencyDescriptor对象,进行依赖查找,找到当前方法参数所匹配的Bean对象。
- 将DependencyDescriptor对象和所找到的结果对象beanName封装成一个ShortcutDependencyDescriptor对象作为缓存,比如如果当前Bean是原型Bean,那么下次再来创建该Bean时,就可以直接拿缓存的结果对象beanName去BeanFactory中去那bean对象了,不用再次进行查找了
- 利用反射将找到的所有结果对象传给当前方法,并执行。
核心方法的实现
1.resolveDependency()
该方法表示,传入一个依赖描述(DependencyDescriptor),该方法会根据该依赖描述从BeanFactory中找出对应的唯一的一个Bean对象
@Nullable Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, @Nullable SetautowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException;
DefaultListableBeanFactory中resolveDependency()方法的具体实现,具体流程图:
2.findAutowireCandidates()
@Autowired在依赖注入的时候,他能选择那些Bean进行依赖注入?
findAutowireCandidates()方法是依赖注入的核心
源码流程
- 找出BeanFactory中类型为type的所有的Bean的名字,注意是名字,而不是Bean对象,因为我们可以根据BeanDefinition就能判断和当前type是不是匹配,不用生成Bean对象
- 把resolvableDependencies中key为type的对象找出来并添加到result中
- 遍历根据type找出的beanName,判断当前beanName对应的Bean是不是能够被自动注入
- 先判断beanName对应的BeanDefinition中的autowireCandidate属性,如果为false,表示不能用来进行自动注入,如果为true则继续进行判断
- 判断当前type是不是泛型,如果是泛型是会把容器中所有的beanName找出来的,如果是这种情况,那么在这一步中就要获取到泛型的真正类型,然后进行匹配,如果当前beanName和当前泛型对应的真实类型匹配,那么则继续判断
- 如果当前DependencyDescriptor上存在@Qualifier注解,那么则要判断当前beanName上是否定义了Qualifier,并且是否和当前DependencyDescriptor上的Qualifier相等,相等则匹配
- 经过上述验证之后,当前beanName才能成为一个可注入的,添加到result中
根据类型找BeanName的底层流程:
根据类型找BeanName的执行流程图:
源码分析
protected MapfindAutowireCandidates( @Nullable String beanName, Class> requiredType, DependencyDescriptor descriptor) { // 从BeanFactory中找出和requiredType所匹配的beanName,仅仅是beanName,这些bean不一定经过了实例化,只有到最终确定某个Bean了,如果这个Bean还没有实例化才会真正进行实例化 String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( this, requiredType, true, descriptor.isEager()); Map result = CollectionUtils.newLinkedHashMap(candidateNames.length); // 根据类型从resolvableDependencies中匹配Bean,resolvableDependencies中存放的是类型:Bean对象,比如BeanFactory.class:BeanFactory对象,在Spring启动时设置。 for (Map.Entry , Object> classObjectEntry : this.resolvableDependencies.entrySet()) { // 得到当前Bean的类型 Class> autowiringType = classObjectEntry.getKey(); if (autowiringType.isAssignableFrom(requiredType)) { // 获取缓存中的值 Object autowiringValue = classObjectEntry.getValue(); // 这里会生成一个Bean的名字,放到缓存中的是没有Bean的名字的 autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType); // 类型匹配,将当前值添加进去 if (requiredType.isInstance(autowiringValue)) { result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue); break; } } } // 这里理解就是注入同一个Bean的时候,先考虑同类型的其他Bean for (String candidate : candidateNames) { // 如果不是自己,则判断该candidate到底能不能用来进行自动注入(@Bean(autowireCandidate = true))默认为true if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) { // 不是自己,并且可以注入的时候,调用这个代码:添加候选者 addCandidateEntry(result, candidate, descriptor, requiredType); } } // 为空要么是真的没有匹配的,要么是匹配的自己 if (result.isEmpty()) { // 需要匹配的类型是不是Map、数组之类的 boolean multiple = indicatesMultipleBeans(requiredType); // Consider fallback matches if the first pass failed to find anything... // 如果第一遍找不到任何东西,请考虑回退匹配。 DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch(); // 遍历每个候选者 for (String candidate : candidateNames) { // 不是自己并且可以被注入并且(不是Map、数组之类的或者@Qualifier指定了BeanName的) if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor) && (!multiple || getAutowireCandidateResolver().hasQualifier(descriptor))) { // 添加真正的候选者 addCandidateEntry(result, candidate, descriptor, requiredType); } } // 匹配的是自己,把自己添加到result中。 if (result.isEmpty() && !multiple) { // Consider self references as a final pass... // but in the case of a dependency collection, not the very same bean itself. for (String candidate : candidateNames) { if (isSelfReference(beanName, candidate) && (!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) && isAutowireCandidate(candidate, fallbackDescriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType); } } } } return result; } private void addCandidateEntry(Map candidates, String candidateName, DependencyDescriptor descriptor, Class> requiredType) { // MultiElementDescriptor的逻辑 if (descriptor instanceof MultiElementDescriptor) { Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this); if (!(beanInstance instanceof NullBean)) { candidates.put(candidateName, beanInstance); } } // 单例的逻辑 else if (containsSingleton(candidateName) || (descriptor instanceof StreamDependencyDescriptor && ((StreamDependencyDescriptor) descriptor).isOrdered())) { // 如果在单例池中存在,则直接放入bean对象 Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this); candidates.put(candidateName, (beanInstance instanceof NullBean ? null : beanInstance)); } else { // 将匹配的beanName,以及beanClass存入 candidates.put(candidateName, getType(candidateName)); } }
获取一个类型对应的BeanName:
public static String[] beanNamesForTypeIncludingAncestors( ListableBeanFactory lbf, Class> type, boolean includeNonSingletons, boolean allowEagerInit) { Assert.notNull(lbf, "ListableBeanFactory must not be null"); // 从本容器中找 String[] result = lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit); // 从父容器找并放入result if (lbf instanceof HierarchicalBeanFactory) { HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf; if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { // 递归调用 String[] parentResult = beanNamesForTypeIncludingAncestors( (ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit); // 把从子父Bean工厂找到的值合并去重(有重复用子类的) result = mergeNamesWithParent(result, parentResult, hbf); } } // 返回找到的所有BeanName return result; } public String[] getBeanNamesForType(@Nullable Class> type, boolean includeNonSingletons, boolean allowEagerInit) { // 如果没有冻结,就根据类型去BeanFactory找,如果冻结了,可能就跳过这个if然后去缓存中去拿了 if (!isConfigurationFrozen() || type == null || !allowEagerInit) { return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit); } // 把当前类型所匹配的beanName缓存起来 Map, String[]> cache = (includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType); // 得到缓冲中的BeanName值 String[] resolvedBeanNames = cache.get(type); // 得到的值不为null,直接返回 if (resolvedBeanNames != null) { return resolvedBeanNames; } // 值为null,重新去获取值 resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true); // 进行缓存 if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) { cache.put(type, resolvedBeanNames); } // 返回所有的BeanName return resolvedBeanNames; } private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { List result = new ArrayList<>(); // Check all bean definitions. // 遍历所有的BeanDefinitions for (String beanName : this.beanDefinitionNames) { // Only consider bean as eligible if the bean name is not defined as alias for some other bean. // 跳过别名 if (!isAlias(beanName)) { try { // 得到当前Bean合并后的BeanDefinition RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // Only check bean definition if it is complete. // 判断mbd允不允许获取对应类型 // 首先mdb不能是抽象的,然后allowEagerInit为true,则直接去推测mdb的类型,并进行匹配 // 如果allowEagerInit为false,那就继续判断,如果mdb还没有加载类并且是懒加载的并且不允许提前加载类,那mbd不能用来进行匹配(因为不允许提前加载类,只能在此mdb自己去创建bean对象时才能去创建类) // 如果allowEagerInit为false,并且mbd已经加载类了,或者是非懒加载的,或者允许提前加载类,并且不用必须提前初始化才能获取类型,那么就可以去进行匹配了 // 这个条件有点复杂,但是如果只考虑大部分流程,则可以忽略这个判断,因为allowEagerInit传进来的基本上都是true if (!mbd.isAbstract() && (allowEagerInit || (mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) && !requiresEagerInitForType(mbd.getFactoryBeanName()))) { // 得到是否是FactoryBean boolean isFactoryBean = isFactoryBean(beanName, mbd); // 得到BeanDefinitionHolder BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); // 匹配标志false boolean matchFound = false; // 容许FactoryBean初始化 boolean allowFactoryBeanInit = (allowEagerInit || containsSingleton(beanName)); // 是否非懒加载 boolean isNonLazyDecorated = (dbd != null && !mbd.isLazyInit()); // 当前BeanDefinition不是FactoryBean,就是普通Bean if (!isFactoryBean) { // 在筛选Bean时,如果仅仅只包括单例,但是beanName对应的又不是单例,则忽略 if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) { // 判断类型是否匹配 matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit); } } else { if (includeNonSingletons || isNonLazyDecorated || (allowFactoryBeanInit && isSingleton(beanName, mbd, dbd))) { // 类型匹配-懒加载 matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit); } if (!matchFound) { // In case of FactoryBean, try to match FactoryBean instance itself next. beanName = FACTORY_BEAN_PREFIX + beanName; // 类型匹配-FactoryBean matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit); } } if (matchFound) { // 将匹配到的,添加到结果集 result.add(beanName); } } } catch (CannotLoadBeanClassException | BeanDefinitionStoreException ex) { if (allowEagerInit) { throw ex; } // Probably a placeholder: let's ignore it for type matching purposes. LogMessage message = (ex instanceof CannotLoadBeanClassException ? LogMessage.format("Ignoring bean class loading failure for bean '%s'", beanName) : LogMessage.format("Ignoring unresolvable metadata in bean definition '%s'", beanName)); logger.trace(message, ex); // Register exception, in case the bean was accidentally unresolvable. onSuppressedException(ex); } catch (NoSuchBeanDefinitionException ex) { // Bean definition got removed while we were iterating -> ignore. } } } // Check manually registered singletons too. // 这里的逻辑是在手动注册的bean中看是否有满足条件的 for (String beanName : this.manualSingletonNames) { try { // In case of FactoryBean, match object created by FactoryBean. if (isFactoryBean(beanName)) { if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) { result.add(beanName); // Match found for this bean: do not match FactoryBean itself anymore. continue; } // In case of FactoryBean, try to match FactoryBean itself next. beanName = FACTORY_BEAN_PREFIX + beanName; } // Match raw bean instance (might be raw FactoryBean). if (isTypeMatch(beanName, type)) { result.add(beanName); } } catch (NoSuchBeanDefinitionException ex) { // Shouldn't happen - probably a result of circular reference resolution... logger.trace(LogMessage.format( "Failed to check manually registered singleton with name '%s'", beanName), ex); } } // 返回结果数组 return StringUtils.toStringArray(result); }
判断类型是否匹配:
protected boolean isTypeMatch(String name, ResolvableType typeToMatch, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException { // 判断name所对应的Bean的类型是不是typeToMatch // allowFactoryBeanInit表示允不允许在这里实例化FactoryBean对象 // 如果name是&xxx,那么beanName就是xxx String beanName = transformedBeanName(name); // name是不是&xxx(FactoryBean) boolean isFactoryDereference = BeanFactoryUtils.isFactoryDereference(name); // Check manually registered singletons. // 获取danliBean Object beanInstance = getSingleton(beanName, false); // 获取到了单例Bean,并且不是空的Bean if (beanInstance != null && beanInstance.getClass() != NullBean.class) { // FactoryBean的特殊逻辑 if (beanInstance instanceof FactoryBean) { // FactoryBean的外部的类 if (!isFactoryDereference) { // 调用factoryBean.getObjectType() Class> type = getTypeForFactoryBean((FactoryBean>) beanInstance); // 返回当前类型不为空并且类型是否匹配 return (type != null && typeToMatch.isAssignableFrom(type)); } else { // 返回类型是否匹配 return typeToMatch.isInstance(beanInstance); } } // 不是FactoryBean,就是普通Bean else if (!isFactoryDereference) { // 直接匹配到,返回true。其实常用的方法,看到这一行就可以了 if (typeToMatch.isInstance(beanInstance)) { // Direct match for exposed instance? return true; } // 泛型相关的处理 else if (typeToMatch.hasGenerics() && containsBeanDefinition(beanName)) { // Generics potentially only match on the target class, not on the proxy... RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); Class> targetType = mbd.getTargetType(); if (targetType != null && targetType != ClassUtils.getUserClass(beanInstance)) { // Check raw class match as well, making sure it's exposed on the proxy. Class> classToMatch = typeToMatch.resolve(); if (classToMatch != null && !classToMatch.isInstance(beanInstance)) { return false; } if (typeToMatch.isAssignableFrom(targetType)) { return true; } } ResolvableType resolvableType = mbd.targetType; if (resolvableType == null) { resolvableType = mbd.factoryMethodReturnType; } return (resolvableType != null && typeToMatch.isAssignableFrom(resolvableType)); } } return false; } // 单例池有,但是没有BeanDefinitionMap中没有,返回false。注册了个空实例 else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) { // null instance registered return false; } // No singleton instance found -> check bean definition. BeanFactory parentBeanFactory = getParentBeanFactory(); // 存在父工厂,调用父工厂的isTypeMatch方法 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.isTypeMatch(originalBeanName(name), typeToMatch); } // 单例池中没有name对应的Bean对象,就只能根据BeanDefinition来判断出类型了 // Retrieve corresponding bean definition. RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); // Setup the types that we want to match against Class> classToMatch = typeToMatch.resolve(); if (classToMatch == null) { classToMatch = FactoryBean.class; } // 为了判断当前beanName,是不是classToMatch或FactoryBean Class>[] typesToMatch = (FactoryBean.class == classToMatch ? new Class>[] {classToMatch} : new Class>[] {FactoryBean.class, classToMatch}); // Attempt to predict the bean type Class> predictedType = null; // We're looking for a regular reference but we're a factory bean that has // a decorated bean definition. The target bean should be the same type // as FactoryBean would ultimately return. 啃 if (!isFactoryDereference && dbd != null && isFactoryBean(beanName, mbd)) { // We should only attempt if the user explicitly set lazy-init to true // and we know the merged bean definition is for a factory bean. if (!mbd.isLazyInit() || allowFactoryBeanInit) { RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd); // getObjectType所方法的类型 Class> targetType = predictBeanType(dbd.getBeanName(), tbd, typesToMatch); if (targetType != null && !FactoryBean.class.isAssignableFrom(targetType)) { predictedType = targetType; } } } // If we couldn't use the target type, try regular prediction. if (predictedType == null) { predictedType = predictBeanType(beanName, mbd, typesToMatch); if (predictedType == null) { return false; } } // Attempt to get the actual ResolvableType for the bean. ResolvableType beanType = null; // If it's a FactoryBean, we want to look at what it creates, not the factory class. // BeanDefinition的类型是不是FactoryBean,如果是得先实例化FactoryBean这个对象,然后调用getObjectType方法才能知道具体的类型,前提是allowFactoryBeanInit为true if (FactoryBean.class.isAssignableFrom(predictedType)) { if (beanInstance == null && !isFactoryDereference) { beanType = getTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit); predictedType = beanType.resolve(); if (predictedType == null) { return false; } } } else if (isFactoryDereference) { // Special case: A SmartInstantiationAwareBeanPostProcessor returned a non-FactoryBean // type but we nevertheless are being asked to dereference a FactoryBean... // Let's check the original bean class and proceed with it if it is a FactoryBean. predictedType = predictBeanType(beanName, mbd, FactoryBean.class); if (predictedType == null || !FactoryBean.class.isAssignableFrom(predictedType)) { return false; } } // We don't have an exact type but if bean definition target type or the factory // method return type matches the predicted type then we can use that. if (beanType == null) { ResolvableType definedType = mbd.targetType; if (definedType == null) { definedType = mbd.factoryMethodReturnType; } if (definedType != null && definedType.resolve() == predictedType) { beanType = definedType; } } // If we have a bean type use it so that generics are considered if (beanType != null) { return typeToMatch.isAssignableFrom(beanType); } // If we don't have a bean type, fallback to the predicted type return typeToMatch.isAssignableFrom(predictedType); }
3.依赖注入中泛型注入的实现
在Java反射中,有一个Type接口,表示类型,具体分类为:
- raw types:也就是普通Class
- parameterized types:对应ParameterizedType接口,泛型类型
- array types:对应GenericArrayType,泛型数组
- type variables:对应TypeVariable接口,表示类型变量,也就是所定义的泛型,比如T、K
- primitive types:基本类型,int、boolean
代码解析
代码打印的结果:
public class TypeTest{ private int i; private Integer it; private int[] iarray; private List list; private List slist; private List tlist; private T t; private T[] tarray; public static void main(String[] args) throws NoSuchFieldException { test(TypeTest.class.getDeclaredField("i")); System.out.println("======="); test(TypeTest.class.getDeclaredField("it")); System.out.println("======="); test(TypeTest.class.getDeclaredField("iarray")); System.out.println("======="); test(TypeTest.class.getDeclaredField("list")); System.out.println("======="); test(TypeTest.class.getDeclaredField("slist")); System.out.println("======="); test(TypeTest.class.getDeclaredField("tlist")); System.out.println("======="); test(TypeTest.class.getDeclaredField("t")); System.out.println("======="); test(TypeTest.class.getDeclaredField("tarray")); } public static void test(Field field) { if (field.getType().isPrimitive()) { System.out.println(field.getName() + "是基本数据类型"); } else { System.out.println(field.getName() + "不是基本数据类型"); } if (field.getGenericType() instanceof ParameterizedType) { System.out.println(field.getName() + "是泛型类型"); } else { System.out.println(field.getName() + "不是泛型类型"); } if (field.getType().isArray()) { System.out.println(field.getName() + "是普通数组"); } else { System.out.println(field.getName() + "不是普通数组"); } if (field.getGenericType() instanceof GenericArrayType) { System.out.println(field.getName() + "是泛型数组"); } else { System.out.println(field.getName() + "不是泛型数组"); } if (field.getGenericType() instanceof TypeVariable) { System.out.println(field.getName() + "是泛型变量"); } else { System.out.println(field.getName() + "不是泛型变量"); } } }
Spring中,当注入点是一个泛型时,会进行处理如下处理:
@Component public class UserService extends BaseService{ public void test() { System.out.println(o); } } public class BaseService { @Autowired protected O o; @Autowired protected S s; }
处理流程
- Spring扫描时发现UserService是一个Bean
- 那就取出注入点,也就是BaseService中的两个属性o、s
- 接下来需要按注入点类型进行注入,但是o和s都是泛型,所以Spring需要确定o和s的具体类型。
- 因为当前正在创建的是UserService的Bean,所以可以通过userService.getClass().getGenericSuperclass().getTypeName()获取到具体的泛型信息,比如com.fish.service.BaseService
- 然后再拿到UserService的父类BaseService的泛型变量: for (TypeVariable extends Class>> typeParameter : userService.getClass().getSuperclass().getTypeParameters()) {
System.out.println(typeParameter.getName());
} - 通过上面两段代码,就能知道,o对应的具体就是OrderService,s对应的具体类型就是StockService
- 然后再调用oField.getGenericType()就知道当前field使用的是哪个泛型,就能知道具体类型了
注解讲解
1.@Qualifier
spring官方文档是这样描述它的用法:
使用@Autowired自动注入的时候,可以在属性或参数加上@Qualifier(“xxx”)指定注入到对象;
可以作为筛选的限定符,我们在写自定义的注解时,可以在其定义上增加@Qualifier,来筛选需要的对象。
使用@Autowired自动注入的时候,可以在属性或参数加上@Qualifier(“xxx”)指定注入到对象:
public interface OfficeService { void log(); } @Service("oldOfficeService") public class OldOfficeServiceImpl implements OfficeService { @Override public void log() { System.out.println("i am oldOfficeService"); } } @Service("newOfficeService") public class NewOfficeServiceImpl implements OfficeService { @Override public void log() { System.out.println("i am newOfficeService"); } } public class OfficeController { @Autowired @Qualifier("oldOfficeService") private OfficeService officeService; @RequestMapping("/test") public void test() { // 输出:i am oldOfficeService officeService.log(); } }
可以作为筛选的限定符,我们在写自定义的注解时,可以在其定义上增加@Qualifier,来筛选需要的对象:
// 1.定义两个注解 @Target({ElementType.TYPE, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Qualifier("random") public @interface Random { } @Target({ElementType.TYPE, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Qualifier("roundRobin") public @interface RoundRobin { }
// 2.定义一个接口两个实现类,表示负载均衡 public interface LoadBalance { String select(); } @Component @Random public class RandomStrategy implements LoadBalance { @Override public String select() { return null; } } @Component @RoundRobin public class RoundRobinStrategy implements LoadBalance { @Override public String select() { return null; } }
// 3.使用 @Component public class UserService { @Autowired @RoundRobin private LoadBalance loadBalance; public void test() { System.out.println(loadBalance); } }
第二种用法在开源软件ribbon有使用到,我们使用ribbon的时候一般都有类似这样的代码:
@Configuration public class RestTemplateConfiguration { @Bean @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); } }
为什么这里加上@LoadBalanced既可以实现负载均衡呢?答案就在@LoadBalanced里:
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Qualifier public @interface LoadBalanced { }
@LoadBalanced注解上加了@Qualifier注解,在程序启动初始化的时候,在spring配置类
LoadBalancerAutoConfiguration中会筛选出来所有加了@LoadBalanced注解的RestTemplate对象,执行http请求的时候就可以从按负载均衡规则从list选择RestTemplate执行实际的请求,这样就达到负载均衡的目的。
这就是为什么在RestTemplate上加了@LoadBalanced就可以实现负载均衡的功能,只是普通的注入RestTemplate,就没有负载均衡功能。
2.@Resource
@Resousrce不是Spring提供的,而是Java提供的注解,Spring对@Resource注解提供了支持
@Resource注解和@Autowired注解类似,都用来声明需要自动装配的bean,区别在于@Autowired是类型驱动的注入,而@Resource是名称驱动的注入(如果未添加不同的name属性,哪怕不是同路径下的类同名也会报错)
@Resource有两个属性是比较重要的,分别是name和type;Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。默认按name进行注入。
@Resource底层工作原理: