springboot InstantiationAwareBeanPostProcessor说明


springboot InstantiationAwareBeanPostProcessor说明

                       

                                

*******************

相关类与接口

               

InstantiationAwareBeanPostProcessor

public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
    @Nullable
    default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        return null;
    }

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

    @Nullable
    default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        return null;
    }

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

                    

BeanPostProcessor

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

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

                  

                        

CommonAnnotationBeanPostProcessor:@PostProcessor、@PreDestroy、@Resource

public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {
    @Nullable
    private static final Class<? extends Annotation> webServiceRefClass = loadAnnotationType("javax.xml.ws.WebServiceRef");
    @Nullable
    private static final Class<? extends Annotation> ejbClass = loadAnnotationType("javax.ejb.EJB");
    private static final Set<Class<? extends Annotation>> resourceAnnotationTypes = new LinkedHashSet(4);
    private final Set<String> ignoredResourceTypes = new HashSet(1);
    private boolean fallbackToDefaultTypeMatch = true;
    private boolean alwaysUseJndiLookup = false;
    private transient BeanFactory jndiFactory = new SimpleJndiBeanFactory();
    @Nullable
    private transient BeanFactory resourceFactory;
    @Nullable
    private transient BeanFactory beanFactory;
    @Nullable
    private transient StringValueResolver embeddedValueResolver;
    private final transient Map<String, InjectionMetadata> injectionMetadataCache = new ConcurrentHashMap(256);

    public CommonAnnotationBeanPostProcessor() {
        this.setOrder(2147483644);
        this.setInitAnnotationType(PostConstruct.class);     //初始化注解:PostConstruct
        this.setDestroyAnnotationType(PreDestroy.class);     //销毁注解:PreDestroy
        this.ignoreResourceType("javax.xml.ws.WebServiceContext");
    }

    public void ignoreResourceType(String resourceType) {
    public void setFallbackToDefaultTypeMatch(boolean fallbackToDefaultTypeMatch) {
    public void setAlwaysUseJndiLookup(boolean alwaysUseJndiLookup) {
    public void setJndiFactory(BeanFactory jndiFactory) {
    public void setResourceFactory(BeanFactory resourceFactory) {
    public void setBeanFactory(BeanFactory beanFactory) {


    public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
    public void resetBeanDefinition(String beanName) {


    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
        return null;
    }  //实例化之前不做处理

    public boolean postProcessAfterInstantiation(Object bean, String beanName) {
        return true;
    }  //属性填充时,使用postProcessProperties返回的PropertyValues

    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
        InjectionMetadata metadata = this.findResourceMetadata(beanName, bean.getClass(), pvs);

        try {
            metadata.inject(bean, beanName, pvs);
            return pvs;
        } catch (Throwable var6) {
            throw new BeanCreationException(beanName, "Injection of resource dependencies failed", var6);
        }
    }

    /** @deprecated */
    @Deprecated
    public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
        return this.postProcessProperties(pvs, bean, beanName);
    }


    private InjectionMetadata findResourceMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
    private InjectionMetadata buildResourceMetadata(Class<?> clazz) {

    protected Object buildLazyResourceProxy(final CommonAnnotationBeanPostProcessor.LookupElement element, @Nullable final String requestingBeanName) {

    protected Object getResource(CommonAnnotationBeanPostProcessor.LookupElement element, @Nullable String requestingBeanName) throws NoSuchBeanDefinitionException {
    protected Object autowireResource(BeanFactory factory, CommonAnnotationBeanPostProcessor.LookupElement element, @Nullable String requestingBeanName) throws NoSuchBeanDefinitionException {


    @Nullable
    private static Class<? extends Annotation> loadAnnotationType(String name) {
        try {
            return ClassUtils.forName(name, CommonAnnotationBeanPostProcessor.class.getClassLoader());
        } catch (ClassNotFoundException var2) {
            return null;
        }
    }


    static {
        resourceAnnotationTypes.add(Resource.class);  //静态语句块中添加注解:Resource
        if (webServiceRefClass != null) {             //如果类加载器中有注解:javax.xml.ws.WebServiceRef,则加入注解WebServiceRefClass
            resourceAnnotationTypes.add(webServiceRefClass);
        }

        if (ejbClass != null) {                       //如果类加载器中有注解:javax.ejb.EJB,则加入注解EJB
            resourceAnnotationTypes.add(ejbClass);
        }

    }   


************
内部类:LookupDependencyDescriptor

    private static class LookupDependencyDescriptor extends DependencyDescriptor {
        private final Class<?> lookupType;

        public LookupDependencyDescriptor(Field field, Class<?> lookupType) {
        public LookupDependencyDescriptor(Method method, Class<?> lookupType) {

        public Class<?> getDependencyType() {
            return this.lookupType;
        }
    }



************
内部类:EjbRefElement

    private class EjbRefElement extends CommonAnnotationBeanPostProcessor.LookupElement {
        private final String beanName;

        public EjbRefElement(Member member, AnnotatedElement ae, @Nullable PropertyDescriptor pd) {

        protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) {


************
内部类:WebServiceRefElement

    private class WebServiceRefElement extends CommonAnnotationBeanPostProcessor.LookupElement {
        private final Class<?> elementType;
        private final String wsdlLocation;

        public WebServiceRefElement(Member member, AnnotatedElement ae, @Nullable PropertyDescriptor pd) {

        protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) {


************
内部类:ResourceElement

    private class ResourceElement extends CommonAnnotationBeanPostProcessor.LookupElement {
        private final boolean lazyLookup;

        public ResourceElement(Member member, AnnotatedElement ae, @Nullable PropertyDescriptor pd) {

        protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) {


************
内部类:LookupElement

    protected abstract static class LookupElement extends InjectedElement {
        protected String name = "";
        protected boolean isDefaultName = false;
        protected Class<?> lookupType = Object.class;
        @Nullable
        protected String mappedName;

        public LookupElement(Member member, @Nullable PropertyDescriptor pd) {


        public final String getName() {
        public final Class<?> getLookupType() {

        public final DependencyDescriptor getDependencyDescriptor() {

                 

InitDestroyAnnotationBeanPostProcessor:初始化、销毁处理器

public class InitDestroyAnnotationBeanPostProcessor implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {

    private final transient InitDestroyAnnotationBeanPostProcessor.LifecycleMetadata emptyLifecycleMetadata = new InitDestroyAnnotationBeanPostProcessor.LifecycleMetadata(Object.class, Collections.emptyList(), Collections.emptyList()) {
        public void checkConfigMembers(RootBeanDefinition beanDefinition) {
        }

        public void invokeInitMethods(Object target, String beanName) {
        }

        public void invokeDestroyMethods(Object target, String beanName) {
        }

        public boolean hasDestroyMethods() {
            return false;
        }
    };
    protected transient Log logger = LogFactory.getLog(this.getClass());

    @Nullable
    private Class<? extends Annotation> initAnnotationType;    //初始化注解
    @Nullable
    private Class<? extends Annotation> destroyAnnotationType; //销毁注解
    private int order = 2147483647;
    @Nullable
    private final transient Map<Class<?>, InitDestroyAnnotationBeanPostProcessor.LifecycleMetadata> lifecycleMetadataCache = new ConcurrentHashMap(256);

    public InitDestroyAnnotationBeanPostProcessor() {
    }

    public void setInitAnnotationType(Class<? extends Annotation> initAnnotationType) {
    public void setDestroyAnnotationType(Class<? extends Annotation> destroyAnnotationType) {

    public void setOrder(int order) {
    public int getOrder() {

    public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
        InitDestroyAnnotationBeanPostProcessor.LifecycleMetadata metadata = this.findLifecycleMetadata(beanType);
        metadata.checkConfigMembers(beanDefinition);
    }

    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        InitDestroyAnnotationBeanPostProcessor.LifecycleMetadata metadata = this.findLifecycleMetadata(bean.getClass());

        try {
            metadata.invokeInitMethods(bean, beanName);
            return bean;
        } catch (InvocationTargetException var5) {
            throw new BeanCreationException(beanName, "Invocation of init method failed", var5.getTargetException());
        } catch (Throwable var6) {
            throw new BeanCreationException(beanName, "Failed to invoke init method", var6);
        }
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
        InitDestroyAnnotationBeanPostProcessor.LifecycleMetadata metadata = this.findLifecycleMetadata(bean.getClass());

        try {
            metadata.invokeDestroyMethods(bean, beanName);
        } catch (InvocationTargetException var6) {
            String msg = "Destroy method on bean with name '" + beanName + "' threw an exception";
            if (this.logger.isDebugEnabled()) {
                this.logger.warn(msg, var6.getTargetException());
            } else {
                this.logger.warn(msg + ": " + var6.getTargetException());
            }
        } catch (Throwable var7) {
            this.logger.warn("Failed to invoke destroy method on bean with name '" + beanName + "'", var7);
        }

    }

    public boolean requiresDestruction(Object bean) {
        return this.findLifecycleMetadata(bean.getClass()).hasDestroyMethods();
    }

    private InitDestroyAnnotationBeanPostProcessor.LifecycleMetadata findLifecycleMetadata(Class<?> clazz) {
    private InitDestroyAnnotationBeanPostProcessor.LifecycleMetadata buildLifecycleMetadata(Class<?> clazz) {

    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {


**************
内部类:LifecycleElement

    private static class LifecycleElement {
        private final Method method;
        private final String identifier;

        public LifecycleElement(Method method) {


        public Method getMethod() {
        public String getIdentifier() {

        public void invoke(Object target) throws Throwable {

        public boolean equals(@Nullable Object other) {
        public int hashCode() {


**************
内部类:LifecycleMetadata

    private class LifecycleMetadata {
        private final Class<?> targetClass;
        private final Collection<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> initMethods;
                              //初始化方法,可为多个
        private final Collection<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> destroyMethods;
                              //销毁方法,可为多个
        @Nullable
        private volatile Set<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> checkedInitMethods;
        @Nullable
        private volatile Set<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> checkedDestroyMethods;

        public LifecycleMetadata(Class<?> targetClass, Collection<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> initMethods, Collection<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> destroyMethods) {

        public void checkConfigMembers(RootBeanDefinition beanDefinition) {

        public void invokeInitMethods(Object target, String beanName) throws Throwable {
            Collection<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> checkedInitMethods = this.checkedInitMethods;
            Collection<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> initMethodsToIterate = checkedInitMethods != null ? checkedInitMethods : this.initMethods;
            InitDestroyAnnotationBeanPostProcessor.LifecycleElement element;
            if (!((Collection)initMethodsToIterate).isEmpty()) {
                for(Iterator var5 = ((Collection)initMethodsToIterate).iterator(); var5.hasNext(); element.invoke(target)) {
                        //调用注解的初始化方法
                    element = (InitDestroyAnnotationBeanPostProcessor.LifecycleElement)var5.next();
                    if (InitDestroyAnnotationBeanPostProcessor.this.logger.isTraceEnabled()) {
                        InitDestroyAnnotationBeanPostProcessor.this.logger.trace("Invoking init method on bean '" + beanName + "': " + element.getMethod());
                    }
                }
            }

        }

        public void invokeDestroyMethods(Object target, String beanName) throws Throwable {
            Collection<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> checkedDestroyMethods = this.checkedDestroyMethods;
            Collection<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> destroyMethodsToUse = checkedDestroyMethods != null ? checkedDestroyMethods : this.destroyMethods;
            InitDestroyAnnotationBeanPostProcessor.LifecycleElement element;
            if (!((Collection)destroyMethodsToUse).isEmpty()) {
                for(Iterator var5 = ((Collection)destroyMethodsToUse).iterator(); var5.hasNext(); element.invoke(target)) {
                        //调用注解的销毁方法
                    element = (InitDestroyAnnotationBeanPostProcessor.LifecycleElement)var5.next();
                    if (InitDestroyAnnotationBeanPostProcessor.this.logger.isTraceEnabled()) {
                        InitDestroyAnnotationBeanPostProcessor.this.logger.trace("Invoking destroy method on bean '" + beanName + "': " + element.getMethod());
                    }
                }
            }

        }

        public boolean hasDestroyMethods() {

               

DestructionAwareBeanPostProcessor:销毁接口

public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor {
    void postProcessBeforeDestruction(Object var1, String var2) throws BeansException;

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

                           

                           

AutowiredAnnotationBeanPostProcessor:@Autowired、@Value、@Inject

public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
    protected final Log logger = LogFactory.getLog(this.getClass());
    private final Set<Class<? extends Annotation>> autowiredAnnotationTypes = new LinkedHashSet(4);

    private String requiredParameterName = "required";
    private boolean requiredParameterValue = true;       //是否需要参数值,默认为true
    private int order = 2147483645;

    @Nullable
    private ConfigurableListableBeanFactory beanFactory;
    private final Set<String> lookupMethodsChecked = Collections.newSetFromMap(new ConcurrentHashMap(256));
    private final Map<Class<?>, Constructor<?>[]> candidateConstructorsCache = new ConcurrentHashMap(256);
    private final Map<String, InjectionMetadata> injectionMetadataCache = new ConcurrentHashMap(256);

    public AutowiredAnnotationBeanPostProcessor() {
        this.autowiredAnnotationTypes.add(Autowired.class);  //添加注解:Autowired
        this.autowiredAnnotationTypes.add(Value.class);      //添加注解:Value

        try {
            this.autowiredAnnotationTypes.add(ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
                                          //如果类加载器有javax.inject.Inject,则添加注解Inject
            this.logger.trace("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
        } catch (ClassNotFoundException var2) {
        }

    }

    public void setAutowiredAnnotationType(Class<? extends Annotation> autowiredAnnotationType) {
    public void setAutowiredAnnotationTypes(Set<Class<? extends Annotation>> autowiredAnnotationTypes) {

    public void setRequiredParameterName(String requiredParameterName) {
    public void setRequiredParameterValue(boolean requiredParameterValue) {

    public void setOrder(int order) {
    public int getOrder() {

    public void setBeanFactory(BeanFactory beanFactory) {

    public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
        InjectionMetadata metadata = this.findAutowiringMetadata(beanName, beanType, (PropertyValues)null);
        metadata.checkConfigMembers(beanDefinition);
    }

    public void resetBeanDefinition(String beanName) {
        this.lookupMethodsChecked.remove(beanName);
        this.injectionMetadataCache.remove(beanName);
    }

    @Nullable
    public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeanCreationException {


    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
        InjectionMetadata metadata = this.findAutowiringMetadata(beanName, bean.getClass(), pvs);

        try {
            metadata.inject(bean, beanName, pvs);
            return pvs;
        } catch (BeanCreationException var6) {
            throw var6;
        } catch (Throwable var7) {
            throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", var7);
        }
    }

    public void processInjection(Object bean) throws BeanCreationException {

    private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
    private InjectionMetadata buildAutowiringMetadata(Class<?> clazz) {
    private MergedAnnotation<?> findAutowiredAnnotation(AccessibleObject ao) {


    protected boolean determineRequiredStatus(MergedAnnotation<?> ann) {
    protected <T> Map<String, T> findAutowireCandidates(Class<T> type) throws BeansException {

    private void registerDependentBeans(@Nullable String beanName, Set<String> autowiredBeanNames) {
    private Object resolvedCachedArgument(@Nullable String beanName, @Nullable Object cachedArgument) {


***********
内部类:ShortcutDependencyDescriptor

    private static class ShortcutDependencyDescriptor extends DependencyDescriptor {
        private final String shortcut;
        private final Class<?> requiredType;

        public ShortcutDependencyDescriptor(DependencyDescriptor original, String shortcut, Class<?> requiredType) {

        public Object resolveShortcut(BeanFactory beanFactory) {


***********
内部类:AutowiredMethodElement

    private class AutowiredMethodElement extends InjectedElement {
        private final boolean required;
        private volatile boolean cached;
        @Nullable
        private volatile Object[] cachedMethodArguments;

        public AutowiredMethodElement(Method method, boolean required, @Nullable PropertyDescriptor pd) {

        protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {

        private Object[] resolveCachedArguments(@Nullable String beanName) {
        private Object[] resolveMethodArguments(Method method, Object bean, @Nullable String beanName) {


***********
内部类:AutowiredFieldElement

    private class AutowiredFieldElement extends InjectedElement {
        private final boolean required;
        private volatile boolean cached;
        @Nullable
        private volatile Object cachedFieldValue;

        public AutowiredFieldElement(Field field, boolean required) {

        protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {

        private Object resolveFieldValue(Field field, Object bean, @Nullable String beanName) {

                    

SmartInstantiationAwareBeanPostProcessor

public interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor {
    @Nullable
    default Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException {
        return null;
    }

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

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

                      

MergedBeanDefinitionPostProcessor

public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor {
    void postProcessMergedBeanDefinition(RootBeanDefinition var1, Class<?> var2, String var3);

    default void resetBeanDefinition(String beanName) {
    }
}

                      

AbstractAutowireCapableBeanFactory

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {


*********
createBean

    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("Creating instance of bean '" + beanName + "'");
        }

        RootBeanDefinition mbdToUse = mbd;
        Class<?> resolvedClass = this.resolveBeanClass(mbd, beanName, new Class[0]);
        if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
            mbdToUse = new RootBeanDefinition(mbd);
            mbdToUse.setBeanClass(resolvedClass);
        }

        try {
            mbdToUse.prepareMethodOverrides();
        } catch (BeanDefinitionValidationException var9) {
            throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", var9);
        }

        Object beanInstance;
        try {
            beanInstance = this.resolveBeforeInstantiation(beanName, mbdToUse);
                           //实例化之前解析
            if (beanInstance != null) {
                return beanInstance;
            }
        } catch (Throwable var10) {
            throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", var10);
        }

        try {
            beanInstance = this.doCreateBean(beanName, mbdToUse, args);
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("Finished creating instance of bean '" + beanName + "'");
            }

            return beanInstance;
        } catch (ImplicitlyAppearedSingletonException | BeanCreationException var7) {
            throw var7;
        } catch (Throwable var8) {
            throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", var8);
        }
    }



    @Nullable
    protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
                     //实例化之前解析
        Object bean = null;
        if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
            if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
                                
                Class<?> targetType = this.determineTargetType(beanName, mbd);
                if (targetType != null) {
                               //判断targetType是否有InstantiationAwareBeanPostProcessor,
                               //如果有,则调用postProcessBeforeInstantiation方法
                    bean = this.applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                    if (bean != null) {
                        bean = this.applyBeanPostProcessorsAfterInitialization(bean, beanName);
                    }  //如果bean不为null,调用postProcessAfterInitialization
                }
            }

            mbd.beforeInstantiationResolved = bean != null;
        }

        return bean;
    }

    @Nullable
    protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
        Iterator var3 = this.getBeanPostProcessorCache().instantiationAware.iterator();

        Object result;
        do {
            if (!var3.hasNext()) {
                return null;
            }

            InstantiationAwareBeanPostProcessor bp = (InstantiationAwareBeanPostProcessor)var3.next();
            result = bp.postProcessBeforeInstantiation(beanClass, beanName);
                        //调用postProcessBeforeInstantiation
        } while(result == null);

        return result;
    }

    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;

        Object current;
        for(Iterator var4 = this.getBeanPostProcessors().iterator(); var4.hasNext(); result = current) {
            BeanPostProcessor processor = (BeanPostProcessor)var4.next();
            current = processor.postProcessAfterInitialization(result, beanName);
                                //调用postProcessAfterInitialization方法
            if (current == null) {
                return result;
            }
        }

        return result;
    }



    protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
        }

        if (instanceWrapper == null) {
            instanceWrapper = this.createBeanInstance(beanName, mbd, args);
        }   //创建bean实例

        Object bean = instanceWrapper.getWrappedInstance();
        Class<?> beanType = instanceWrapper.getWrappedClass();
        if (beanType != NullBean.class) {
            mbd.resolvedTargetType = beanType;
        }

        synchronized(mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    this.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                } catch (Throwable var17) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", var17);
                }

                mbd.postProcessed = true;
            }
        }

        boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
        if (earlySingletonExposure) {
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references");
            }

            this.addSingletonFactory(beanName, () -> {
                return this.getEarlyBeanReference(beanName, mbd, bean);
            });
        }

        Object exposedObject = bean;

        try {
            this.populateBean(beanName, mbd, instanceWrapper);                  //属性填充
            exposedObject = this.initializeBean(beanName, exposedObject, mbd);  //初始化
        } catch (Throwable var18) {
            if (var18 instanceof BeanCreationException && beanName.equals(((BeanCreationException)var18).getBeanName())) {
                throw (BeanCreationException)var18;
            }

            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", var18);
        }

        if (earlySingletonExposure) {
            Object earlySingletonReference = this.getSingleton(beanName, false);
            if (earlySingletonReference != null) {
                if (exposedObject == bean) {
                    exposedObject = earlySingletonReference;
                } else if (!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
                    String[] dependentBeans = this.getDependentBeans(beanName);
                    Set<String> actualDependentBeans = new LinkedHashSet(dependentBeans.length);
                    String[] var12 = dependentBeans;
                    int var13 = dependentBeans.length;

                    for(int var14 = 0; var14 < var13; ++var14) {
                        String dependentBean = var12[var14];
                        if (!this.removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                            actualDependentBeans.add(dependentBean);
                        }
                    }

                    if (!actualDependentBeans.isEmpty()) {
                        throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
                    }
                }
            }
        }

        try {
            this.registerDisposableBeanIfNecessary(beanName, bean, mbd);
            return exposedObject;
        } catch (BeanDefinitionValidationException var16) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", var16);
        }
    }


*************
属性填充

    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
        if (bw == null) {
            if (mbd.hasPropertyValues()) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
            }
        } else {
            if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
                Iterator var4 = this.getBeanPostProcessorCache().instantiationAware.iterator();

                while(var4.hasNext()) {
                    InstantiationAwareBeanPostProcessor bp = (InstantiationAwareBeanPostProcessor)var4.next();
                    if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                        return;
                    }
                }
            }

            PropertyValues pvs = mbd.hasPropertyValues() ? mbd.getPropertyValues() : null;
            int resolvedAutowireMode = mbd.getResolvedAutowireMode();
            if (resolvedAutowireMode == 1 || resolvedAutowireMode == 2) {
                MutablePropertyValues newPvs = new MutablePropertyValues((PropertyValues)pvs);
                if (resolvedAutowireMode == 1) {
                    this.autowireByName(beanName, mbd, bw, newPvs);
                }

                if (resolvedAutowireMode == 2) {
                    this.autowireByType(beanName, mbd, bw, newPvs);
                }

                pvs = newPvs;
            }

            boolean hasInstAwareBpps = this.hasInstantiationAwareBeanPostProcessors();
            boolean needsDepCheck = mbd.getDependencyCheck() != 0;
            PropertyDescriptor[] filteredPds = null;
            if (hasInstAwareBpps) {
                if (pvs == null) {
                    pvs = mbd.getPropertyValues();
                }

                PropertyValues pvsToUse;
                for(Iterator var9 = this.getBeanPostProcessorCache().instantiationAware.iterator(); var9.hasNext(); pvs = pvsToUse) {                    
                    InstantiationAwareBeanPostProcessor bp = (InstantiationAwareBeanPostProcessor)var9.next();
                    pvsToUse = bp.postProcessProperties((PropertyValues)pvs, bw.getWrappedInstance(), beanName);
                        //InstantiationAwareBeanPostProcessor返回的PropertyValues
                        //pvs = pvsToUse,待注入的属性值

                    if (pvsToUse == null) {
                        if (filteredPds == null) {
                            filteredPds = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                        }

                        pvsToUse = bp.postProcessPropertyValues((PropertyValues)pvs, filteredPds, bw.getWrappedInstance(), beanName);
                        if (pvsToUse == null) {
                            return;
                        }
                    }
                }
            }

            if (needsDepCheck) {
                if (filteredPds == null) {
                    filteredPds = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                }

                this.checkDependencies(beanName, mbd, filteredPds, (PropertyValues)pvs);
            }

            if (pvs != null) {
                this.applyPropertyValues(beanName, mbd, bw, (PropertyValues)pvs);
            }   //如果pvs不为空则注入属性值

        }
    }



*************
初始化

    protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged(() -> {
                this.invokeAwareMethods(beanName, bean);
                return null;
            }, this.getAccessControlContext());
        } else {
            this.invokeAwareMethods(beanName, bean);
        }  //调用aware方法(BeanNameAware、BeanClassLoaderAware、BeanFactoryAware)

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
        }  //初始化前调用applyBeanPostProcessorsBeforeInitialization

        try {
            this.invokeInitMethods(beanName, wrappedBean, mbd);
                 //调用initMethod(InitializingBean、指定的initMethodName)
        } catch (Throwable var6) {
            throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
        }

        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }        //调用applyBeanPostProcessorsAfterInitialization

        return wrappedBean;
    }

    private void invokeAwareMethods(String beanName, Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware)bean).setBeanName(beanName);
            }

            if (bean instanceof BeanClassLoaderAware) {
                ClassLoader bcl = this.getBeanClassLoader();
                if (bcl != null) {
                    ((BeanClassLoaderAware)bean).setBeanClassLoader(bcl);
                }
            }

            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware)bean).setBeanFactory(this);
            }
        }

    }

    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;

        Object current;
        for(Iterator var4 = this.getBeanPostProcessors().iterator(); var4.hasNext(); result = current) {
            BeanPostProcessor processor = (BeanPostProcessor)var4.next();
            current = processor.postProcessBeforeInitialization(result, beanName);
                               //调用postProcessBeforeInitialization
            if (current == null) {
                return result;
            }
        }

        return result;
    }

    protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd) throws Throwable {
        boolean isInitializingBean = bean instanceof InitializingBean;
        if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
            }

            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(() -> {
                        ((InitializingBean)bean).afterPropertiesSet();
                        return null;
                    }, this.getAccessControlContext());
                } catch (PrivilegedActionException var6) {
                    throw var6.getException();
                }
            } else {
                ((InitializingBean)bean).afterPropertiesSet();
            }
        }

        if (mbd != null && bean.getClass() != NullBean.class) {
            String initMethodName = mbd.getInitMethodName();
            if (StringUtils.hasLength(initMethodName) && (!isInitializingBean || !"afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) {
                this.invokeCustomInitMethod(beanName, bean, mbd);
            }
        }

    }

    protected void invokeCustomInitMethod(String beanName, Object bean, RootBeanDefinition mbd) throws Throwable {
        String initMethodName = mbd.getInitMethodName();
        Assert.state(initMethodName != null, "No init method set");
        Method initMethod = mbd.isNonPublicAccessAllowed() ? BeanUtils.findMethod(bean.getClass(), initMethodName, new Class[0]) : ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName, new Class[0]);
        if (initMethod == null) {
            if (mbd.isEnforceInitMethod()) {
                throw new BeanDefinitionValidationException("Could not find an init method named '" + initMethodName + "' on bean with name '" + beanName + "'");
            } else {
                if (this.logger.isTraceEnabled()) {
                    this.logger.trace("No default init method named '" + initMethodName + "' found on bean with name '" + beanName + "'");
                }

            }
        } else {
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("Invoking init method  '" + initMethodName + "' on bean with name '" + beanName + "'");
            }

            Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod);
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(() -> {
                    ReflectionUtils.makeAccessible(methodToInvoke);
                    return null;
                });

                try {
                    AccessController.doPrivileged(() -> {
                        return methodToInvoke.invoke(bean);
                    }, this.getAccessControlContext());
                } catch (PrivilegedActionException var10) {
                    InvocationTargetException ex = (InvocationTargetException)var10.getException();
                    throw ex.getTargetException();
                }
            } else {
                try {
                    ReflectionUtils.makeAccessible(methodToInvoke);
                    methodToInvoke.invoke(bean);
                } catch (InvocationTargetException var9) {
                    throw var9.getTargetException();
                }
            }

        }
    }

    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;

        Object current;
        for(Iterator var4 = this.getBeanPostProcessors().iterator(); var4.hasNext(); result = current) {
            BeanPostProcessor processor = (BeanPostProcessor)var4.next();
            current = processor.postProcessAfterInitialization(result, beanName);
            if (current == null) {
                return result;
            }
        }

        return result;
    }

                    

                    

*******************

示例

                       

*****************

pojo 层

              

Person

@Data
public class Person {

    private String name;
    private Integer age;
}

              

People

@Data
public class People {

    private String name;
    private Integer age;
}

                 

Student

@Data
public class Student implements InitializingBean, DisposableBean {

    private String name;
    private Integer age;

    @PostConstruct
    public void fun(){
        System.out.println("student postConstruct");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("student afterPropertiesSet:"+ this);
    }

    public void customInit(){
        System.out.println("student 自定义初始化方法:customInit");
    }

    @PreDestroy
    public void destroy(){
        System.out.println("student preDestroy");
    }

    public void customDestroy(){
        System.out.println("student 自定义销毁方法:customDestroy");
    }
}

              

*****************

config 层

               

DataConfig

@Configuration
public class DataConfig {

    @Bean("person")
    public Person initPerson(){
        Person person=new Person();
        person.setName("初始化名称 瓜田李下");
        person.setAge(20);

        return person;
    }

    @Bean(name = "student",initMethod = "customInit",destroyMethod = "customDestroy")
    public Student initStudent(){
        Student student=new Student();
        student.setName("初始化名称 海贼王");
        student.setAge(20);

        return student;
    }

    @Bean("people")
    public People initPeople(){
        People people=new People();
        people.setName("初始化名称 火影忍者");
        people.setAge(20);

        return people;
    }
}

                    

CustomInstantiationAwareBeanPostProcessor

@Configuration
public class CustomInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if (beanClass.getSimpleName().equals("Person")){
            Person person=new Person();
            person.setName("修改后名称 瓜田李下");
            person.setAge(20);
            System.out.println(person);

            return person;
        }

        return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInstantiation(beanClass, beanName);
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if (bean instanceof People){
            return true;
        }

        return InstantiationAwareBeanPostProcessor.super.postProcessAfterInstantiation(bean, beanName);
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        if (bean instanceof People){
            System.out.println(beanName+"  "+bean+"  "+pvs.getPropertyValues().length);
            MutablePropertyValues mutablePropertyValues=(MutablePropertyValues)pvs;
            mutablePropertyValues.addPropertyValue("name","修改后名称 火影忍者");

            return mutablePropertyValues;
        }

        return InstantiationAwareBeanPostProcessor.super.postProcessProperties(pvs, bean, beanName);
    }
}

                  

*****************

controller 层

                

HelloController

@RestController
public class HelloController {

    @Resource
    private Person person;

    @Resource
    private People people;

    @Resource
    private Student student;

    @RequestMapping("/hello")
    public String hello(){
        System.out.println(person);
        System.out.println(people);
        System.out.println(student);

        return "success";
    }
}

                      

                                  

*******************

测试输出

              

启动后,控制台输出

2021-08-07 19:49:48.008  INFO 15652 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-08-07 19:49:48.008  INFO 15652 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1443 ms
Person(name=修改后名称 瓜田李下, age=20)
people  People(name=初始化名称 火影忍者, age=20)  0

# 执行顺序:@PostConstruct、afterpropertiesSet、自定义初始化方法(initMethod)
student postConstruct
student afterPropertiesSet:Student(name=初始化名称 海贼王, age=20)
student 自定义初始化方法:customInit

2021-08-07 19:49:48.625  INFO 15652 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-08-07 19:49:48.635  INFO 15652 --- [           main] tiationAwareBeanPostProcessorApplication : Started SpringbootInstantiationAwareBeanPostProcessorApplication in 2.505 seconds (JVM running for 3.54)

                    

localhost:8080/hello,控制台输出:

Person(name=修改后名称 瓜田李下, age=20)
People(name=修改后名称 火影忍者, age=20)
Student(name=初始化名称 海贼王, age=20)

# person属性在postProcessBeforeInstantiation中修改
# people属性在postProcessAfterInstantiation、postProcessProperties中修改

                                 

                                         

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值