• Spring源码之Bean生命周期


    https://www.jianshu.com/p/1dec08d290c1
    https://www.cnblogs.com/zrtqsk/p/3735273.html

    总结

    1. 将class文件加载成BeanDefinition,并向IOC容器中进行注册
    2. 在实例化前,能通过实现BeanFactoryPostProcessor,进行BeanDefinition注册,设置Bean属性值等功能
    3. 在createBean时,实现SmartInstantiationAwareBeanPostProcessor或InstantiationAwareBeanPostProcessor接口的postProcessBeforeInstantiation的方法
    4. Bean 实例化(createBeanInstance)
    5. 实现InstantiationAwareBeanPostProcessor接口,在populateBean中调用postProcessAfterInstantiation
    6. initializeBean时,调用invokeAwareMethods(),实现类通过实现BeanFactoryAware, BeanNameAware进行自定义一些功能
    7. 实现BeanPostProcessor的postProcessBeforeInitialization()
    8. @PostConstruct
    9. invokeInitMethods反射方式进行初始化
    10. afterPropertiesSet(),初始化后进行属性设置
    11. BeanPostProcessor#postProcessAfterInitialization()
    12. @PreDestroy
    13. destroy()

    加载成BeanDefinition,并向IOC容器中进行注册

    详见前文《Spring源码之IOC容器创建、BeanDefinition加载和注册和IOC容器依赖注入》

    BeanFactoryPostProcessor#invokeBeanFactoryPostProcessors()

    在PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors()方法中完成invokeBeanDefinitionRegistryPostProcessors() BeanDefinition的注册后,会调用各BeanFactoryPostProcessor的postProcessBeanFactory方法,此时可自定义实现BeanFactoryPostProcessor的postProcessBeanFactory方法,进行属性添加等功能。

    一个例子:

    @Component
    public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
        int i = 1;
    
        public MyBeanFactoryPostProcessor() {
            super();
            System.out.println("这是BeanFactoryPostProcessor实现类构造器!!");
        }
    
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
                throws BeansException {
    
            if(beanFactory.getBeanDefinition("person") != null && i == 1) {
                i--;
                System.out.println("BeanFactoryPostProcessor调用postProcessBeanFactory方法");
            }
    
            BeanDefinition bd = beanFactory.getBeanDefinition("person");
            bd.getPropertyValues().addPropertyValue("name", "Carl");
        }
    }
    
    postProcessBeforeInstantiation()

    在createBean时,实例化(Instantiation Bean)前,自定义实现SmartInstantiationAwareBeanPostProcessor接口的postProcessBeforeInstantiation的方法,可做一些自定义处理。

    @Override
    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
    	Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
    	......
    }
    

    一个例子:

    @Component
    public class MyInstantiationAwareBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor {
    
        // 接口方法、实例化Bean之前调用
        @Override
        public Object postProcessBeforeInstantiation(Class beanClass,String beanName) throws BeansException {
    
            if(beanName.equals("person")) {
                System.out.println("InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法");
            }
            return null;
        }
    }
    
    实例化时初始化构造器

    由AbstractAutowireCapableBeanFactory#doCreateBean()入口,通过createBeanInstance去进行实例化

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

    SimpleInstantiationStrategy#instantiate()

    @Override
    public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
        ......
        return BeanUtils.instantiateClass(constructorToUse);
    }
    
    postProcessAfterInstantiation

    在AbstractAutowireCapableBeanFactory#populateBean()中

    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    	......
    
    	// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
    	// state of the bean before properties are set. This can be used, for example,
    	// to support styles of field injection.
    	if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
    		for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
    			if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
    				return;
    			}
    		}
    	}
    }
    
    postProcessPropertyValues()
    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    
    		PropertyDescriptor[] filteredPds = null;
    		if (hasInstAwareBpps) {
    			for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
    				if (pvsToUse == null) {
    					......
    					pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
    					......
    				}
    				pvs = pvsToUse;
    			}
    		}
    	}
    

    例子:

    @Component
    public class MyInstantiationAwareBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor {
        // 接口方法、设置某个属性时调用
        @Override
        public PropertyValues postProcessPropertyValues(PropertyValues pvs,PropertyDescriptor[] pds, Object bean, String beanName)
                throws BeansException {
            if(beanName.equals("person")) {
                System.out.println("InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法");
            }
    
            return pvs;
        }
    }
    
    invokeAwareMethods()
    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 = getBeanClassLoader();
    			if (bcl != null) {
    				((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
    			}
    		}
    		if (bean instanceof BeanFactoryAware) {
    			((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
    		}
    	}
    }
    

    例子:

    @Component
    public class Person implements BeanFactoryAware, BeanNameAware,InitializingBean, DisposableBean {
        @Override
        public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
            System.out.println("【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()");
            this.beanFactory = beanFactory;
        }
    
        // 这是BeanNameAware接口方法
        @Override
        public void setBeanName(String beanName) {
            System.out.println("【BeanNameAware接口】调用BeanNameAware.setBeanName()");
            this.beanName = beanName;
        }
    }
    
    postProcessBeforeInitialization()

    执行初始化

    exposedObject = initializeBean(beanName, exposedObject, mbd);
    
    protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
    	......
    	Object wrappedBean = bean;
    	if (mbd == null || !mbd.isSynthetic()) {
    		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    	}
    }
    

    一个例子:

    @Component
    public class MyBeanPostProcessor implements BeanPostProcessor {
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName)
                throws BeansException {
            if(beanName.equals("person")) {
                System.out.println("BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!");
            }
            return bean;
        }
    }
    
    @PostConstruct

    InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization()

    通过反射方式去调用@PostConstruct注解的方法

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    	LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
    	try {
    		metadata.invokeInitMethods(bean, beanName);
    	}
    	......
    	return bean;
    }
    

    例子:

    @PostConstruct
    public void myInit() {
        System.out.println("【init-method】调用<bean>的init-method属性指定的初始化方法");
    }
    
    初始化(invokeInitMethods)

    AbstractAutowireCapableBeanFactory#initializeBean()

    protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
        try {
    		invokeInitMethods(beanName, wrappedBean, mbd);
    	}
    }
    
    afterPropertiesSet()

    AbstractAutowireCapableBeanFactory#invokeInitMethods()

    protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
    		throws Throwable {
    
    	((InitializingBean) bean).afterPropertiesSet();
        .......
    }
    
    BeanPostProcessor#postProcessAfterInitialization()
    protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
    	if (mbd == null || !mbd.isSynthetic()) {
    		wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    	}
    	......
    }
    

    例子:

    @Component
    public class MyBeanPostProcessor implements BeanPostProcessor {
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName)
                throws BeansException {
            if(beanName.equals("person")){
                System.out.println("BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!");
            }
    
            return bean;
        }
    }
    
    @PreDestroy

    在DisposableBeanAdapter#destroy()方法中,调用InitDestroyAnnotationBeanPostProcessor#postProcessBeforeDestruction(),最后通过反射执行@PreDestroy方法

    @Override
    public void destroy() {
    	if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
    		for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
    			processor.postProcessBeforeDestruction(this.bean, this.beanName);
    		}
    	}
    }
    

    例子

    @Component
    public class Person implements BeanFactoryAware, BeanNameAware,InitializingBean, DisposableBean {
        @PreDestroy
        public void myDestory() {
            System.out.println("【destroy-method】调用<bean>的destroy-method属性指定的初始化方法");
        }
    }
    
    destroy
    @Component
    public class Person implements BeanFactoryAware, BeanNameAware,InitializingBean, DisposableBean {
        @Override
        public void destroy() throws Exception {
            System.out.println("【DiposibleBean接口】调用DiposibleBean.destory()");
        }
    }
    
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出。
  • 相关阅读:
    UVA 11806 组合数学+容斥
    Educational Codeforces Round 37 (Rated for Div. 2) G
    java 5 线程池
    团队-象棋游戏-项目进度
    结对-五子棋-测试过程
    结对-五子棋游戏-开发过程
    课后作业-阅读任务-阅读提问-2
    20171006-构建之法:现代软件工程-阅读笔记
    结队-五子棋游戏-项目进度
    团队-象棋游戏-代码设计规范
  • 原文地址:https://www.cnblogs.com/caozibiao/p/13995893.html
Copyright © 2020-2023  润新知