Spring source code-bean life cycle

Architecture diagram

Insert picture description here

bean life cycle

  1. Bean establishment
    Load the class into the spring container, such as @Component

  2. Generate BeanDefinition
    When the bean is loaded into the spring container, a corresponding BeanDefinition is generated to store the information of the bean, including:
    beanClass, scope, abstractFlag, lazyInit, autowireMode, dependencyCheck, dependsOn, autowireCandidate, primary, qualifiers, instanceSupplier, nonPublicAccessAllowed, lenientConstructorResolution, factoryBeanName, factoryMethodName…


  3. Form a BeanFactory (DefaultListableBeanFactory;) in the beanFactory:

    • beanDefinitionMap:存储beanDefinition(DefaultListableBeanFactory;)
     private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap(256);
    
    • singletonObjects: Store loaded beans (DefaultSingletonBeanRegistry)
     private final Map<String, Object> singletonObjects = new ConcurrentHashMap(256);
    
    • beanDefinitionNames: Store the name list of beanDefinition (DefaultListableBeanFactory)
    private volatile List<String> beanDefinitionNames = new ArrayList(256);
    
    • factoryBeaObjectCache
    • aliasMap
    • BeanPostProcessor
  4. Create bean object

    • Instantiate
    • Inferred construction method
    • AOP
    • Dependency injection
    • PostConstruct
    • Aware
    • InitializingBean
  5. Stored in the singleton pool (Map<BeanName,Object>)

Source code analysis

Source code of org.springframework.context.support.AbstractApplicationContext.refresh():

@Override
	public void refresh() throws BeansException, IllegalStateException {
    
    
		synchronized (this.startupShutdownMonitor) {
    
    
			// 准备上下文的刷新.
			prepareRefresh();

			// 刷新并获取bean工厂
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			//准备beanFactory
			prepareBeanFactory(beanFactory);

			try {
    
    
				// beanFacory 后置处理器.供子类实现
				postProcessBeanFactory(beanFactory);

				// 调用上下文中注册为bean的工厂后置处理器
				invokeBeanFactoryPostProcessors(beanFactory);

				//  注册Bean后置处理器
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// 初始化特定上下文子类中的其他特殊bean
				onRefresh();

				// 注册监听器
				registerListeners();

				// 例化所有剩余的(非延迟初始化)单例.
				finishBeanFactoryInitialization(beanFactory);

				// 发布相应事件,完成刷新
				finishRefresh();
			}

			catch (BeansException ex) {
    
    
				if (logger.isWarnEnabled()) {
    
    
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				// 发生异常,则销毁已经实例化的bean
				destroyBeans();

				// 重置active标识
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
    
    
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}

1. Before instantiation

Register BeanDefinition

  1. ImportBeanDefinitionRegister
public class MyBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    
    
    /**
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
    
    

        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(MyAnnotationScan.class.getName());

        //拿到包
        Object value = annotationAttributes.get("value");
        //掃描
        System.out.println(value);
        List<Class> mappers = new ArrayList<>();
        mappers.add(UserMapper.class);
        mappers.add(OrderMapper.class);

        for (Class mapper : mappers) {
    
    
            //生成一个空的beanDefinition
            BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition();
            AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
            beanDefinition.setBeanClass(MyFactoryBean.class);
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(mapper);
            registry.registerBeanDefinition(mapper.getSimpleName(),beanDefinition);
        }
    }
}

bea factory post processor BeanFactoryPostProcessor

@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    
    
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    
    


        GenericBeanDefinition bd = (GenericBeanDefinition) beanFactory.getBeanDefinition("userService");
        Class<?> beanClass = bd.getBeanClass();
        Object userService = beanFactory.getBean("userService");
      /*  System.out.println(beanClass);
        bd.setBeanClass(UserEntity.class);*/
    }
}

2. Bean establishment:

The container looks for the definition information of the Bean and instantiates it.

3. Attribute injection:

Using dependency injection (IOC), Spring configures all properties of Bean according to Bean definition information

4.BeanNameAware 的 setBeanName () :

If the Bean class implements the org.springframework.beans.BeanNameAware interface, the factory calls the setBeanName() method of the Bean to pass the ID of the Bean.

/**
 * @author XingShuaiJiang
 * 可设置beanName的值
 */
@Component
public class MyBeanNameAware implements BeanNameAware {
    
    
    @Override
    public void setBeanName(String s) {
    
    

    }
}

5. BeanFactoryAware的setBeanFactory():

If the Bean class implements the org.springframework.beans.factory.BeanFactoryAware interface, the factory calls the setBeanFactory() method to pass in the factory itself.

/**
 * @author 
 * 可设置beanFactory
 */
@Component
public class MyBeanFactoryAware implements BeanFactoryAware {
    
    
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
    
    
        
    }
}

6. BeanPostProcessors的ProcessBeforeInitialization()

If there is org.springframework.beans.factory.config.BeanPostProcessors associated with the Bean, then its postProcessBeforeInitialization() method will be called.

/**
 * bean创建成功后的 后置处理器
 * 经常被用作是Bean内容的更改,并且由于这个是在Bean初始化结束时调用那个的方法,也可以被应用于内存或缓存技术;
 */
 @Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    
    
    /**
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     * 在实例化bean之前调用
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    
    
        return null;
    }

    /**
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     * 在实例化bean之后调用
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    
    
        return null;
    }
}

7.initializingBean 的 afterPropertiesSet () :

If the Bean class has implemented the org.springframework.beans.factory.InitializingBean interface, execute its afterProPertiesSet() method

/**
 * 初始化bean
 */
@Component
class MyInitializingBean implements InitializingBean {
    
    
    @Override
    public void afterPropertiesSet() throws Exception {
    
    

    }
}

8. If the attribute in BeanDefinition defines init-method:

You can use the "init-method" attribute in the Bean definition file to set the method name. For example:

If there are the above settings, the initBean() method will be executed when the execution reaches this stage

9.BeanPostProcessors的ProcessaAfterInitialization()

If any BeanPostProcessors instance is associated with the Bean instance, execute the ProcessaAfterInitialization() method of the BeanPostProcessors instance

/**
 * bean创建成功后的 后置处理器
 * 经常被用作是Bean内容的更改,并且由于这个是在Bean初始化结束时调用那个的方法,也可以被应用于内存或缓存技术;
 */
 @Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    
    
    /**
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     * 在实例化bean之前调用
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    
    
        return null;
    }

    /**
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     * 在实例化bean之后调用
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    
    
        return null;
    }
}

10.DisposableBean的destroy()

When the container is closed, if the Bean class implements the org.springframework.beans.factory.DisposableBean interface, its destroy() method is executed.


/**
 * 销毁bean
 */
@Component
public class MyDisposableBean implements DisposableBean {
    
    
    @Override
    public void destroy() throws Exception {
    
    

    }
}

Guess you like

Origin blog.csdn.net/jinian2016/article/details/109132340