热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

腾讯分析系统架构解析论文_spring系统架构源码解析BeanPostProcessor

说在前面前期回顾sharding-jdbc源码解析更新完毕spring源码解析更新完毕spring-mvc源码解析更新完毕spring-boot源码解析更新完毕rocketmq源码

说在前面

前期回顾

sharding-jdbc源码解析 更新完毕

spring源码解析 更新完毕

spring-mvc源码解析 更新完毕

spring-boot源码解析 更新完毕

rocketmq源码解析 更新完毕

dubbo源码解析 更新完毕

netty源码解析 更新完毕

spring系统架构源码解析 更新中

spring-mvc系统架构源码解析 更新中

spring-boot系统架构源码解析 更新中

dubbo系统架构源码解析 更新中

rocketmq系统架构源码解析 更新中

github https://github.com/tianheframe

rocketmq源码解析 更新完毕

dubbo源码解析 更新完毕

netty源码解析 更新完毕

sharding-jdbc源码解析 更新完毕

dubbo系统架构源码解析 更新中

rocketmq系统架构源码解析 更新中

源码解析

d5cb05d36864a23fd6e4b027fb3022dc.png

beanPostProcessor的目的是为了对beanDefinition、bean初始化过程进行干预处理。

BeanPostProcessor工厂钩子接口

@Nullable default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; }

在bean初始化之前调用返回处理后的bean,类似于InitializingBean接口的afterPropertiesSet方法或者bean的init方法。

@Nullable default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; }

在bean初始化之后调用返回处理后的bean,如InitializingBean的afterPropertiesSet或自定义init-method执行之后。

DestructionAwareBeanPostProcessor 下级子接口,bean销毁前的处理器。

void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException;

在bean销毁之前执行,可以执行bean的销毁方法,如DisposableBean的destroy方法。这个方法仅限于单例bean。

default boolean requiresDestruction(Object bean) { return true; }

确定给定的bean实例是否需要此后置处理器,默认true。

org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor用于在运行时合并BeanDefinition的后处理器回调接口,在bean初始化之前可以添加一些缓存的元数据,也可以修改BeanDefinition,只允许修改定义属性。

void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class> beanType, String beanName);

对指定bean的给定合并bean定义进行后处理。

org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor bean实例化之前、实例化后的处理器接口,在属性设置和自动注入之前。一般用于禁止特定bean的默认实例化,这个接口一般在spring框架内部使用,开发中建议使用InstantiationAwareBeanPostProcessorAdapter。

@Nullable default Object postProcessBeforeInstantiation(Class> beanClass, String beanName) throws BeansException { return null; }

在bean初始化之前执行这个方法,返回的bean对象可以是一个代替目标bean使用的代理,有效地抑制了目标bean的默认实例化。这个方法不会应用于有factoryMethod的bean。

default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { return true; }

通过构造方法或工厂方法初始化bean之后,在属性设置或自动依赖注入之前执行,可以对bean实例执行自定义字段注入的回调处理,默认返回true。

@Nullable default PropertyValues postProcessPropertyValues( PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { return pvs; }

在BeanFactory将给定的属性值依赖注入到指定的bean之前后置处理。

org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor检查最后处理bean类型的回调,这个接口一般在spring框架内部使用,开发中一般使用InstantiationAwareBeanPostProcessorAdapter。

@Nullable default Class> predictBeanType(Class> beanClass, String beanName) throws BeansException { return null; }

返回bean的类型,默认返回null。

@Nullable default Constructor>[] determineCandidateConstructors(Class> beanClass, String beanName) throws BeansException { return null; }

指定这个bean的候选构造器。

default Object getEarlyBeanReference(Object bean, String beanName) throws BeansException { return bean; }

获取指定bean的早期引用,一般用于解决循环依赖,默认按原样返回指定的bean。

org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter抽象类是org.springframework.beans.factory.config.BeanPostProcessor、org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor、org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor接口的默认适配实现,开发中一般不直接使用这三个接口,继承这个抽象类。

org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor调用带init和destory方法的beanPostProcessor实现,org.springframework.beans.factory.InitializingBean 、org.springframework.beans.factory.DisposableBean,nit和destroy注释可以应用于任何可见性的方法:public、package-protected、protected或private。可以注释多个这样的方法,但是建议只分别注释一个init方法和一个destroy方法。@javax.annotation.PostConstruct、@javax.annotation.PreDestroy 带有这两个注解的初始化、销毁方法。

@Nullable private Class extends Annotation> initAnnotationType; @Nullable private Class extends Annotation> destroyAnnotationType;

保存init注解的类型和destory注解的类型。

&#64;Nullable private final transient Map, LifecycleMetadata> lifecycleMetadataCache &#61; new ConcurrentHashMap<>(256);

保存init和destory方法的元数据。

org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor#postProcessMergedBeanDefinition

&#64;Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class> beanType, String beanName) { LifecycleMetadata metadata &#61; findLifecycleMetadata(beanType); metadata.checkConfigMembers(beanDefinition); }

org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor#findLifecycleMetadata

private LifecycleMetadata findLifecycleMetadata(Class> clazz) { if (this.lifecycleMetadataCache &#61;&#61; null) { // Happens after deserialization, during destruction...在反物质化之后&#xff0c;在销毁过程中…… return buildLifecycleMetadata(clazz); } // Quick check on the concurrent map first, with minimal locking.首先快速检查并发映射&#xff0c;并使用最少的锁。 LifecycleMetadata metadata &#61; this.lifecycleMetadataCache.get(clazz); if (metadata &#61;&#61; null) { synchronized (this.lifecycleMetadataCache) { metadata &#61; this.lifecycleMetadataCache.get(clazz); if (metadata &#61;&#61; null) { metadata &#61; buildLifecycleMetadata(clazz); this.lifecycleMetadataCache.put(clazz, metadata); } return metadata; } } return metadata; }

org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor#buildLifecycleMetadata

private LifecycleMetadata buildLifecycleMetadata(final Class> clazz) { final boolean debug &#61; logger.isDebugEnabled(); LinkedList initMethods &#61; new LinkedList<>(); LinkedList destroyMethods &#61; new LinkedList<>(); Class> targetClass &#61; clazz; do { final LinkedList currInitMethods &#61; new LinkedList<>(); final LinkedList currDestroyMethods &#61; new LinkedList<>(); ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() { &#64;Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {// 判断方法上是否有&#64;PostConstruct这个注解 if (initAnnotationType !&#61; null && method.isAnnotationPresent(initAnnotationType)) { LifecycleElement element &#61; new LifecycleElement(method); currInitMethods.add(element); if (debug) { logger.debug("Found init method on class [" &#43; clazz.getName() &#43; "]: " &#43; method); } }// &#64;PreDestroy 判断方法上是否有这个注解 if (destroyAnnotationType !&#61; null && method.isAnnotationPresent(destroyAnnotationType)) { currDestroyMethods.add(new LifecycleElement(method)); if (debug) { logger.debug("Found destroy method on class [" &#43; clazz.getName() &#43; "]: " &#43; method); } } } }); initMethods.addAll(0, currInitMethods); destroyMethods.addAll(currDestroyMethods); targetClass &#61; targetClass.getSuperclass(); } while (targetClass !&#61; null && targetClass !&#61; Object.class); return new LifecycleMetadata(clazz, initMethods, destroyMethods); }

解析待&#64;javax.annotation.PostConstruct、&#64;javax.annotation.PreDestroy的初始化、销毁的方法。

org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization

&#64;Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { LifecycleMetadata metadata &#61; findLifecycleMetadata(bean.getClass()); try { metadata.invokeInitMethods(bean, beanName); } catch (InvocationTargetException ex) { throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException()); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Failed to invoke init method", ex); } return bean; }

&#64;Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; }

在bean初始化之后执行方法。

org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor#postProcessBeforeDestruction

&#64;Override public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {// 找到bean创建和销毁的metadata信息 LifecycleMetadata metadata &#61; findLifecycleMetadata(bean.getClass()); try {// 执行bean的销毁方法 metadata.invokeDestroyMethods(bean, beanName); } catch (InvocationTargetException ex) { String msg &#61; "Invocation of destroy method failed on bean with name &#39;" &#43; beanName &#43; "&#39;"; if (logger.isDebugEnabled()) { logger.warn(msg, ex.getTargetException()); } else { logger.warn(msg &#43; ": " &#43; ex.getTargetException()); } } catch (Throwable ex) { logger.error("Failed to invoke destroy method on bean with name &#39;" &#43; beanName &#43; "&#39;", ex); } }

在bean销毁之前执行的方法。

org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.LifecycleMetadata#invokeDestroyMethods执行销毁方法

public void invokeDestroyMethods(Object target, String beanName) throws Throwable { Collection checkedDestroyMethods &#61; this.checkedDestroyMethods; Collection destroyMethodsToUse &#61; (checkedDestroyMethods !&#61; null ? checkedDestroyMethods : this.destroyMethods); if (!destroyMethodsToUse.isEmpty()) { boolean debug &#61; logger.isDebugEnabled(); for (LifecycleElement element : destroyMethodsToUse) { if (debug) { logger.debug("Invoking destroy method on bean &#39;" &#43; beanName &#43; "&#39;: " &#43; element.getMethod()); }// 执行bean的销毁方法 element.invoke(target); } } }

public void invokeInitMethods(Object target, String beanName) throws Throwable { Collection checkedInitMethods &#61; this.checkedInitMethods; Collection initMethodsToIterate &#61; (checkedInitMethods !&#61; null ? checkedInitMethods : this.initMethods); if (!initMethodsToIterate.isEmpty()) { boolean debug &#61; logger.isDebugEnabled(); for (LifecycleElement element : initMethodsToIterate) { if (debug) { logger.debug("Invoking init method on bean &#39;" &#43; beanName &#43; "&#39;: " &#43; element.getMethod()); } element.invoke(target); } } }

执行bean的init方法。

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor 自动注入带注解的属性&#xff0c;setter方法和其他注入方式&#xff0c;检查&#64;Autowired、&#64;Value、&#64;Inject注解。找到一个构造参数进行注入&#xff0c;如果有多个构造参数可以加注入注解&#xff0c;这些构造参数可以是非public的&#xff0c;这个注解和context:annotation-config、context:component-scan等价。这个处理器还处理&#64;Lookup注解&#xff0c;这个注解用来标注prototype类型的bean在单例bean中每次获取不同的对象&#xff0c;底层是cglib动态代理实现。

private final Set> autowiredAnnotationTypes &#61; new LinkedHashSet<>();

自动依赖注入的注解类型。

private final Map, Constructor>[]> candidateConstructorsCache &#61; new ConcurrentHashMap<>(256);

候选的构造方法缓存。

private final Map injectionMetadataCache &#61; new ConcurrentHashMap<>(256);

依赖注入的方法。

依赖注入的类型包括&#64;Autowired、&#64;Value、&#64;Inject注解。

&#64;Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class> beanType, String beanName) {、// 找到自动注入的元数据 InjectionMetadata metadata &#61; findAutowiringMetadata(beanName, beanType, null); metadata.checkConfigMembers(beanDefinition); }

执行BeanDefinition的后置处理方法。

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#findAutowiringMetadata查询依赖注入的元数据

private InjectionMetadata findAutowiringMetadata(String beanName, Class> clazz, &#64;Nullable PropertyValues pvs) { // Fall back to class name as cache key, for backwards compatibility with custom callers.返回到类名作为缓存键&#xff0c;以便向后兼容自定义调用程序。 String cacheKey &#61; (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); // Quick check on the concurrent map first, with minimal locking.首先快速检查并发映射&#xff0c;并使用最少的锁。 InjectionMetadata metadata &#61; this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { synchronized (this.injectionMetadataCache) { metadata &#61; this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { if (metadata !&#61; null) { metadata.clear(pvs); }// 构建自动准入的元数据 metadata &#61; buildAutowiringMetadata(clazz); this.injectionMetadataCache.put(cacheKey, metadata); } } } return metadata; }

查询自动注入元数据。

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#buildAutowiringMetadata

private InjectionMetadata buildAutowiringMetadata(final Class> clazz) { LinkedList elements &#61; new LinkedList<>(); Class> targetClass &#61; clazz; do { final LinkedList currElements &#61; new LinkedList<>(); ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() { &#64;Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {// 查找依赖注入注解的属性值 AnnotationAttributes ann &#61; AutowiredAnnotationBeanPostProcessor.this.findAutowiredAnnotation(field); if (ann !&#61; null) {// 属性是静态的 if (Modifier.isStatic(field.getModifiers())) { if (logger.isWarnEnabled()) { logger.warn("Autowired annotation is not supported on static fields: " &#43; field); } return; }// 判断required的值 boolean required &#61; AutowiredAnnotationBeanPostProcessor.this.determineRequiredStatus(ann); currElements.add(new AutowiredFieldElement(field, required)); } } }); ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() { &#64;Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {// 找到依赖注入方法的桥接方法&#xff0c;这里是桥接模式实现 Method bridgedMethod &#61; BridgeMethodResolver.findBridgedMethod(method); if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { return; }// 找到桥接方法上的注解 AnnotationAttributes ann &#61; AutowiredAnnotationBeanPostProcessor.this.findAutowiredAnnotation(bridgedMethod); if (ann !&#61; null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { if (Modifier.isStatic(method.getModifiers())) { if (logger.isWarnEnabled()) { logger.warn("Autowired annotation is not supported on static methods: " &#43; method); } return; } if (method.getParameterCount() &#61;&#61; 0) { if (logger.isWarnEnabled()) { logger.warn("Autowired annotation should only be used on methods with parameters: " &#43; method); } }// 确定是否是必须的 boolean required &#61; AutowiredAnnotationBeanPostProcessor.this.determineRequiredStatus(ann);// 查找方法的属性 PropertyDescriptor pd &#61; BeanUtils.findPropertyForMethod(bridgedMethod, clazz); currElements.add(new AutowiredMethodElement(method, required, pd)); } } }); elements.addAll(0, currElements); targetClass &#61; targetClass.getSuperclass(); } while (targetClass !&#61; null && targetClass !&#61; Object.class); return new InjectionMetadata(clazz, elements); }

查找属性上的&#64;Autowired、&#64;Value、&#64;Inject注解的值&#xff0c;如果属性是静态的警告&#xff0c;不建议依赖注入的属性是静态的&#xff0c;解析required是否必须注入一个可用的属性值&#xff0c;查找类上方法的桥接方法的依赖注入注解&#xff0c;解析required是否必须注入一个可用的属性值&#xff0c;找到的结果最后构建依赖注入元数据。

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#determineCandidateConstructors

&#64;Override &#64;Nullable public Constructor>[] determineCandidateConstructors(Class> beanClass, final String beanName) throws BeanCreationException { // Let&#39;s check for lookup methods here..让我们检查查找方法这里.. if (!this.lookupMethodsChecked.contains(beanName)) { try { ReflectionUtils.doWithMethods(beanClass, method -> { Lookup lookup &#61; method.getAnnotation(Lookup.class); if (lookup !&#61; null) { Assert.state(beanFactory !&#61; null, "No BeanFactory available"); LookupOverride override &#61; new LookupOverride(method, lookup.value()); try { RootBeanDefinition mbd &#61; (RootBeanDefinition) beanFactory.getMergedBeanDefinition(beanName); mbd.getMethodOverrides().addOverride(override); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(beanName, "Cannot apply &#64;Lookup to beans without corresponding bean definition"); } } }); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Lookup method resolution failed", ex); } this.lookupMethodsChecked.add(beanName); } // Quick check on the concurrent map first, with minimal locking. Constructor>[] candidateConstructors &#61; this.candidateConstructorsCache.get(beanClass); if (candidateConstructors &#61;&#61; null) { // Fully synchronized resolution now... synchronized (this.candidateConstructorsCache) { candidateConstructors &#61; this.candidateConstructorsCache.get(beanClass); if (candidateConstructors &#61;&#61; null) { Constructor>[] rawCandidates; try { rawCandidates &#61; beanClass.getDeclaredConstructors(); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Resolution of declared constructors on bean Class [" &#43; beanClass.getName() &#43; "] from ClassLoader [" &#43; beanClass.getClassLoader() &#43; "] failed", ex); } List> candidates &#61; new ArrayList<>(rawCandidates.length); Constructor> requiredConstructor &#61; null; Constructor> defaultConstructor &#61; null; Constructor> primaryConstructor &#61; BeanUtils.findPrimaryConstructor(beanClass); int nonSyntheticConstructors &#61; 0; for (Constructor> candidate : rawCandidates) { if (!candidate.isSynthetic()) { nonSyntheticConstructors&#43;&#43;; } else if (primaryConstructor !&#61; null) { continue; } AnnotationAttributes ann &#61; findAutowiredAnnotation(candidate); if (ann &#61;&#61; null) { Class> userClass &#61; ClassUtils.getUserClass(beanClass); if (userClass !&#61; beanClass) { try { Constructor> superCtor &#61; userClass.getDeclaredConstructor(candidate.getParameterTypes()); ann &#61; findAutowiredAnnotation(superCtor); } catch (NoSuchMethodException ex) { // Simply proceed, no equivalent superclass constructor found... } } } if (ann !&#61; null) { if (requiredConstructor !&#61; null) { throw new BeanCreationException(beanName, "Invalid autowire-marked constructor: " &#43; candidate &#43; ". Found constructor with &#39;required&#39; Autowired annotation already: " &#43; requiredConstructor); } boolean required &#61; determineRequiredStatus(ann); if (required) { if (!candidates.isEmpty()) { throw new BeanCreationException(beanName, "Invalid autowire-marked constructors: " &#43; candidates &#43; ". Found constructor with &#39;required&#39; Autowired annotation: " &#43; candidate); } requiredConstructor &#61; candidate; } candidates.add(candidate); } else if (candidate.getParameterCount() &#61;&#61; 0) { defaultConstructor &#61; candidate; } } if (!candidates.isEmpty()) { // Add default constructor to list of optional constructors, as fallback. if (requiredConstructor &#61;&#61; null) { if (defaultConstructor !&#61; null) { candidates.add(defaultConstructor); } else if (candidates.size() &#61;&#61; 1 && logger.isWarnEnabled()) { logger.warn("Inconsistent constructor declaration on bean with name &#39;" &#43; beanName &#43; "&#39;: single autowire-marked constructor flagged as optional - " &#43; "this constructor is effectively required since there is no " &#43; "default constructor to fall back to: " &#43; candidates.get(0)); } } candidateConstructors &#61; candidates.toArray(new Constructor>[0]); } else if (rawCandidates.length &#61;&#61; 1 && rawCandidates[0].getParameterCount() > 0) { candidateConstructors &#61; new Constructor>[] {rawCandidates[0]}; } else if (nonSyntheticConstructors &#61;&#61; 2 && primaryConstructor !&#61; null && defaultConstructor !&#61; null && !primaryConstructor.equals(defaultConstructor)) { candidateConstructors &#61; new Constructor>[] {primaryConstructor, defaultConstructor}; } else if (nonSyntheticConstructors &#61;&#61; 1 && primaryConstructor !&#61; null) { candidateConstructors &#61; new Constructor>[] {primaryConstructor}; } else { candidateConstructors &#61; new Constructor>[0]; } this.candidateConstructorsCache.put(beanClass, candidateConstructors); } } } return (candidateConstructors.length > 0 ? candidateConstructors : null); }

如果beanName上不包括lookup的方法&#xff0c;循环获取这个类上的所有方法的&#64;Lookup注解&#xff0c;找到了这个注解&#xff0c;从BeanFactory中获取beanName的mergedBeanDefinition&#xff0c;标识beanDefinition中的需要覆盖的方法&#xff0c;这类是cglib动态代理会覆盖方法。

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#determineCandidateConstructors

&#64;Override &#64;Nullable public Constructor>[] determineCandidateConstructors(Class> beanClass, final String beanName) throws BeanCreationException { // Let&#39;s check for lookup methods here..让我们检查查找方法这里.. if (!this.lookupMethodsChecked.contains(beanName)) { try { ReflectionUtils.doWithMethods(beanClass, method -> { Lookup lookup &#61; method.getAnnotation(Lookup.class); if (lookup !&#61; null) { Assert.state(beanFactory !&#61; null, "No BeanFactory available"); LookupOverride override &#61; new LookupOverride(method, lookup.value()); try { RootBeanDefinition mbd &#61; (RootBeanDefinition) beanFactory.getMergedBeanDefinition(beanName); mbd.getMethodOverrides().addOverride(override); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(beanName, "Cannot apply &#64;Lookup to beans without corresponding bean definition"); } } }); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Lookup method resolution failed", ex); } this.lookupMethodsChecked.add(beanName); } // Quick check on the concurrent map first, with minimal locking.首先快速检查并发映射&#xff0c;并使用最少的锁。 Constructor>[] candidateConstructors &#61; this.candidateConstructorsCache.get(beanClass); if (candidateConstructors &#61;&#61; null) { // Fully synchronized resolution now...完全同步的分辨率现在… synchronized (this.candidateConstructorsCache) { candidateConstructors &#61; this.candidateConstructorsCache.get(beanClass); if (candidateConstructors &#61;&#61; null) { Constructor>[] rawCandidates; try { rawCandidates &#61; beanClass.getDeclaredConstructors(); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Resolution of declared constructors on bean Class [" &#43; beanClass.getName() &#43; "] from ClassLoader [" &#43; beanClass.getClassLoader() &#43; "] failed", ex); } List> candidates &#61; new ArrayList<>(rawCandidates.length); Constructor> requiredConstructor &#61; null; Constructor> defaultConstructor &#61; null;// 找到beanClass的唯一的构造方法 Constructor> primaryConstructor &#61; BeanUtils.findPrimaryConstructor(beanClass); int nonSyntheticConstructors &#61; 0; for (Constructor> candidate : rawCandidates) { if (!candidate.isSynthetic()) { nonSyntheticConstructors&#43;&#43;; } else if (primaryConstructor !&#61; null) { continue; }// 找到构造方法上的依赖注入的注解 AnnotationAttributes ann &#61; findAutowiredAnnotation(candidate); if (ann &#61;&#61; null) {// 如果beanClass是cglib动态代理的类找到此类的父类 Class> userClass &#61; ClassUtils.getUserClass(beanClass); if (userClass !&#61; beanClass) { try { Constructor> superCtor &#61; userClass.getDeclaredConstructor(candidate.getParameterTypes());// 找到父类构造方法上的依赖注入的注解 ann &#61; findAutowiredAnnotation(superCtor); } catch (NoSuchMethodException ex) { // Simply proceed, no equivalent superclass constructor found...简单地继续&#xff0c;没有找到等价的超类构造函数… } } } if (ann !&#61; null) { if (requiredConstructor !&#61; null) { throw new BeanCreationException(beanName, "Invalid autowire-marked constructor: " &#43; candidate &#43; ". Found constructor with &#39;required&#39; Autowired annotation already: " &#43; requiredConstructor); }// 查询required属性 boolean required &#61; determineRequiredStatus(ann); if (required) { if (!candidates.isEmpty()) { throw new BeanCreationException(beanName, "Invalid autowire-marked constructors: " &#43; candidates &#43; ". Found constructor with &#39;required&#39; Autowired annotation: " &#43; candidate); } requiredConstructor &#61; candidate; } candidates.add(candidate); } else if (candidate.getParameterCount() &#61;&#61; 0) { defaultConstructor &#61; candidate; } } if (!candidates.isEmpty()) { // Add default constructor to list of optional constructors, as fallback.将默认构造函数作为回退添加到可选构造函数列表中。 if (requiredConstructor &#61;&#61; null) { if (defaultConstructor !&#61; null) { candidates.add(defaultConstructor); } else if (candidates.size() &#61;&#61; 1 && logger.isWarnEnabled()) { logger.warn("Inconsistent constructor declaration on bean with name &#39;" &#43; beanName &#43; "&#39;: single autowire-marked constructor flagged as optional - " &#43; "this constructor is effectively required since there is no " &#43; "default constructor to fall back to: " &#43; candidates.get(0)); } } candidateConstructors &#61; candidates.toArray(new Constructor>[0]); } else if (rawCandidates.length &#61;&#61; 1 && rawCandidates[0].getParameterCount() > 0) { candidateConstructors &#61; new Constructor>[] {rawCandidates[0]}; } else if (nonSyntheticConstructors &#61;&#61; 2 && primaryConstructor !&#61; null && defaultConstructor !&#61; null && !primaryConstructor.equals(defaultConstructor)) { candidateConstructors &#61; new Constructor>[] {primaryConstructor, defaultConstructor}; } else if (nonSyntheticConstructors &#61;&#61; 1 && primaryConstructor !&#61; null) { candidateConstructors &#61; new Constructor>[] {primaryConstructor}; } else { candidateConstructors &#61; new Constructor>[0]; } this.candidateConstructorsCache.put(beanClass, candidateConstructors); } } } return (candidateConstructors.length > 0 ? candidateConstructors : null); }

确定候选的构造方法&#xff0c;如果beanName上没有lookup的方法&#xff0c;循环这个类上的方法获取方法上的&#64;Lookup注解&#xff0c;如果找到了标识beanDefinition中需要方法覆盖&#xff0c;否则查询指定beanClass的候选构造方法&#xff0c;找到唯一的构造方法&#xff0c;查询构造方法上的依赖注入的注解&#xff0c;如果没找到&#xff0c;如果这个beanClass是cglib动态类的类型就查询这个类的父类的构造方法上方的依赖注入的注解&#xff0c;获取required属性&#xff0c;返回候选的构造方法集合。

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#postProcessPropertyValues

&#64;Override public PropertyValues postProcessPropertyValues( PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException { InjectionMetadata metadata &#61; findAutowiringMetadata(beanName, bean.getClass(), pvs); try { metadata.inject(bean, beanName, pvs); } catch (BeanCreationException ex) { throw ex; } catch (Throwable ex) { throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex); } return pvs; }

找到bean上的制动注入的元数据&#xff0c;进行依赖注入。

org.springframework.beans.factory.annotation.InjectionMetadata#inject

public void inject(Object target, &#64;Nullable String beanName, &#64;Nullable PropertyValues pvs) throws Throwable { Collection checkedElements &#61; this.checkedElements; Collection elementsToIterate &#61; (checkedElements !&#61; null ? checkedElements : this.injectedElements); if (!elementsToIterate.isEmpty()) { boolean debug &#61; logger.isDebugEnabled(); for (InjectedElement element : elementsToIterate) { if (debug) { logger.debug("Processing injected element of bean &#39;" &#43; beanName &#43; "&#39;: " &#43; element); } element.inject(target, beanName, pvs); } } }

org.springframework.beans.factory.annotation.InjectionMetadata.InjectedElement#inject

protected void inject(Object target, &#64;Nullable String requestingBeanName, &#64;Nullable PropertyValues pvs) throws Throwable {// 如果是属性调用属性的set方法进行设置值 if (this.isField) { Field field &#61; (Field) this.member; ReflectionUtils.makeAccessible(field); field.set(target, getResourceToInject(target, requestingBeanName)); } else {// 如果已经注入过跳过 if (checkPropertySkipping(pvs)) { return; } try {// 如果是构造方法或者工厂方法调用方法注入属性值 Method method &#61; (Method) this.member; ReflectionUtils.makeAccessible(method); method.invoke(target, getResourceToInject(target, requestingBeanName)); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } }

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#processInjection

public void processInjection(Object bean) throws BeanCreationException { Class> clazz &#61; bean.getClass(); InjectionMetadata metadata &#61; findAutowiringMetadata(clazz.getName(), clazz, null); try { metadata.inject(bean, null, null); } catch (BeanCreationException ex) { throw ex; } catch (Throwable ex) { throw new BeanCreationException( "Injection of autowired dependencies failed for class [" &#43; clazz &#43; "]", ex); } }

处理&#64;Autowired的属性和方法&#xff0c;查询类上属性和方法的自动注入元数据进行注入&#xff0c;属性注入就是调用属性的set方法或者调用构造方法和工厂方设置依赖注入的属性值。

private void registerDependentBeans(&#64;Nullable String beanName, Set autowiredBeanNames) { if (beanName !&#61; null) { for (String autowiredBeanName : autowiredBeanNames) { if (this.beanFactory !&#61; null && this.beanFactory.containsBean(autowiredBeanName)) { this.beanFactory.registerDependentBean(autowiredBeanName, beanName); } if (logger.isDebugEnabled()) { logger.debug("Autowiring by type from bean name &#39;" &#43; beanName &#43; "&#39; to bean named &#39;" &#43; autowiredBeanName &#43; "&#39;"); } } } }

如果BeanFactory中包含指定的beanDefinition注册依赖注入对的bean。

org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor 这个处理器和context:annotation-config、context:component-scan标签结合使用。

private Class extends Annotation> requiredAnnotationType &#61; Required.class;

默认检查的注解是&#64;Required注解。

&#64;Override public void setBeanFactory(BeanFactory beanFactory) { if (beanFactory instanceof ConfigurableListableBeanFactory) { this.beanFactory &#61; (ConfigurableListableBeanFactory) beanFactory; } }

这个类实现了BeanFactoryAware接口覆盖这个方法设置BeanFactory。

&#64;Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class> beanType, String beanName) { }

这个类实现了beanDefinition后置处理器的方法&#xff0c;子类可以覆盖这个方法默认什么也不处理。

org.springframework.beans.factory.config.BeanFactoryPostProcessor BeanFactory后置处理器&#xff0c;允许修改beanDefinition&#xff0c;修改bean的属性值&#xff0c;在创建bean之前执行。

org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory 应用程序上下文初始化之后修改BeanFactory&#xff0c;BeanDefinition都已加载但是还没实例化&#xff0c;允许覆盖和添加属性。

org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor BeanDefinitionRegistry后置处理器&#xff0c;可以注册更多的beanDefinition。

void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

应用上下文初始化完毕后可以修改BeanDefinition注册表&#xff0c;在初始化bean实例化之前&#xff0c;可以在下个后置处理阶段之前可以注册更多的BeanDefinition。

说在最后

本次解析仅代表个人观点&#xff0c;仅供参考。

7cf405acbc2bbb4f90a3b5b0ccbca22b.gif

扫码进入技术微信群

6513a550e7670b42da199fbd246a6bdc.png钉钉技术群

67f4535a15ab7511b5c68241ed6c86c5.png

qq群

b8d574082ef364c680beb1642a9b951c.png




推荐阅读
author-avatar
WLII庾斌_787
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有