Spring源码之Bean生命周期
https://www.jianshu.com/p/1dec08d290c1
https://www.cnblogs.com/zrtqsk/p/3735273.html
总结
- 将class文件加载成BeanDefinition,并向IOC容器中进行注册
- 在实例化前,能通过实现BeanFactoryPostProcessor,进行BeanDefinition注册,设置Bean属性值等功能
- 在createBean时,实现SmartInstantiationAwareBeanPostProcessor或InstantiationAwareBeanPostProcessor接口的postProcessBeforeInstantiation的方法
- Bean 实例化(createBeanInstance)
- 实现InstantiationAwareBeanPostProcessor接口,在populateBean中调用postProcessAfterInstantiation
- initializeBean时,调用invokeAwareMethods(),实现类通过实现BeanFactoryAware, BeanNameAware进行自定义一些功能
- 实现BeanPostProcessor的postProcessBeforeInitialization()
- @PostConstruct
- invokeInitMethods反射方式进行初始化
- afterPropertiesSet(),初始化后进行属性设置
- BeanPostProcessor#postProcessAfterInitialization()
- @PreDestroy
- 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()");
}
}
上一篇: 浅谈Angular 的变化检测的方法