Spring IoC-Bean生命周期

概述

通过依赖注入的方式, 将Bean的生命周期交由容器(ApplicationContext)来管理. 一个Bean生命周是指bean的初始化开始到最终销毁的一段时间, 这是一个Bean的完整的周期过程. 在Spring IoC容器中, 为用户提供了各类回调来使得用户感知bean的生命周期.

Bean生命周期感知回调

BeanFactory容器定义的Bean生命周期回调

BeanFactory容器应该尽可能提供的感知回调(具体请参考BeanFactory的参考页面), 节选部分:
Spring IoC-Bean生命周期_第1张图片

实现Bean生命周期回调示例

java代码

public class User implements BeanFactoryAware, BeanNameAware, InitializingBean, DisposableBean,
        EnvironmentAware, EmbeddedValueResolverAware, ResourceLoaderAware, ApplicationEventPublisherAware,
        MessageSourceAware, ApplicationContextAware{
     
    private int id;
    private String name;
    private int age;

    public User() {
     
        System.out.println("[Constructor] init the bean");
    }

    public void setId(int id) {
     
        System.out.println("[setId] set the id, value: " + id);
        this.id = id;
    }

    public void setName(String name) {
     
        System.out.println("[setName] set the name, value: " + name);
        this.name = name;
    }

    public void setAge(int age) {
     
        System.out.println("[setAge] set the age, value: " + age);
        this.age = age;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
     
        System.out.println("[setBeanFactory] set the beanFactory, value: ");
    }

    @Override
    public void setBeanName(String name) {
     
        System.out.println("[setBeanName] set the bean name, value: " + name);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
     
        System.out.println("[afterPropertiesSet] afterPropertiesSet.");
    }

    @Override
    public void destroy() throws Exception {
     
        System.out.println("[destroy] destroy.");
    }

    @PostConstruct
    public void postConstruct() {
     
        System.out.println("[postConstruct] postConstruct.");
    }

    @PreDestroy
    public void preDestroy() {
     
        System.out.println("[preDestroy] preDestroy.");
    }

    @Override
    public void setEnvironment(Environment environment) {
     
        System.out.println("[setEnvironment] set the environment, value: ");
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
     
        System.out.println("[setEmbeddedValueResolver] set the resolver, value: ");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
     
        System.out.println("[setApplicationContext] set the applicationContext, value: ");
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
     
        System.out.println("[setApplicationEventPublisher] set the applicationEventPublisher, value: ");
    }

    @Override
    public void setMessageSource(MessageSource messageSource) {
     
        System.out.println("[setMessageSource] set the messageSource, value: ");
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
     
        System.out.println("[setResourceLoader] set the resourceLoader, value: ");
    }
}

// BeanFactory相关, 这个其实不是bean的生命周期, 是容器的生命周期
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
     

    // BeanFactory准备好之后
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
     
        System.out.println("[postProcessBeanFactory]");
        BeanDefinition bd = beanFactory.getBeanDefinition("user");
        bd.getPropertyValues().addPropertyValue("name", "Walter New");
    }
}

//. 与销毁有关的接口
public class MyDestructionAwareBeanPostProcessor implements DestructionAwareBeanPostProcessor {
     
    // 销毁之前
    @Override
    public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
     
        System.out.println("[postProcessBeforeDestruction]");
    }

    // 我也不知道
    @Override
    public boolean requiresDestruction(Object bean) {
     
        System.out.println("[requiresDestruction]");
        return false;
    }

    // 初始化之前
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
     
        System.out.println("[postProcessBeforeInitialization]");
        return bean;
    }

    // 初始化之后
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
     
        System.out.println("[postProcessAfterInitialization]");
        return bean;
    }
}

// 关于Bean初始化的后置处理器
public class MyInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {
     
    public MyInstantiationAwareBeanPostProcessor() {
     
        super();
        System.out.println("[UserInstantiationAwareBeanPostProcessor] init the UserInstantiationAwareBeanPostProcessor");
    }

    // 当初始化bean之前
    @Override
    public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException {
     
        System.out.println("[postProcessBeforeInstantiation]");
        return null;
    }

    // 当初始化bean之后
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
     
        System.out.println("[postProcessAfterInitialization]");
        return null;
    }

    // 当设置晚了properties之后
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName)
            throws BeansException {
     
        System.out.println("[postProcessPropertyValues]");
        return null;
    }
}

public class LifecylceDemo {
     
    public static void main(String[] args) throws InterruptedException {
     
        String cfg1 = "classpath:application-lifecycle.xml";
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(cfg1);
        System.out.println("context init completed");
        System.out.println("start to shutdown the context");
        context.registerShutdownHook();
    }
}

bean的配置文件 classpath:application-lifecycle.xml


<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
       default-autowire="byName">

    <bean id="user" class="lab.anoper.ioc.lifecycle.User" init-method="postConstruct" destroy-method="preDestroy">
        <property name="id" value="1"/>
        <property name="name" value="Walter Yan"/>
        <property name="age" value="25"/>
    bean>

    <bean id="beanPostProcessor" class="lab.anoper.ioc.lifecycle.MyInstantiationAwareBeanPostProcessor"/>
    <bean id="userBeanFactoryPostProcessor" class="lab.anoper.ioc.lifecycle.MyBeanFactoryPostProcessor"/>
    <bean id="myDestructionAwareBeanPostProcessor"
          class="lab.anoper.ioc.lifecycle.MyDestructionAwareBeanPostProcessor"/>
beans>

输出结果:

[postProcessBeanFactory]
[MyInstantiationAwareBeanPostProcessor] init the MyInstantiationAwareBeanPostProcessor
[postProcessBeforeInstantiation]
[Constructor] init the bean
[postProcessPropertyValues]
[setBeanName] set the bean name, value: user
[setBeanFactory] set the beanFactory, value: 
[setEnvironment] set the environment, value: 
[setEmbeddedValueResolver] set the resolver, value: 
[setResourceLoader] set the resourceLoader, value: 
[setApplicationEventPublisher] set the applicationEventPublisher, value: 
[setMessageSource] set the messageSource, value: 
[setApplicationContext] set the applicationContext, value: 
[postProcessBeforeInitialization]
[afterPropertiesSet] afterPropertiesSet.
[postConstruct] postConstruct.
[postProcessAfterInitialization]
[requiresDestruction]
context init completed
start to shutdown the context
[destroy] destroy.
[preDestroy] preDestroy.

结果分析:

  • BeanFactory最先完成准备, 因为它是容器, 但是它的生命周期不是Bean的生命周期.Bean的生命周期是在Bean注册到BeanDefinition中之后才开始的.
  • 在初始化bean之前做了postProcessBeforeInstantiation回调通知.
  • 在调用bean的constructor进行初始化之后随后调用了postProcessPropertyValues回调通知.
  • 在调用bean的afterPropertiesSet方法之前调用了postProcessBeforeInitialization回调通知.
  • 在调用了bean的afterPropertiesSetpostConstruct之后随后调用了postProcessAfterInitialization回调通知.
  • 在容器开始销毁时, 先调用了destroy方法, 随后调用了preDestroy方法.

总结

Spring IoC中提供了两个容器ApplicationContextBeanFactory, 他们管理者Bean的注册, 初始化, 依赖注入, 销毁等周期.
Bean的生命周期就是指从注册到BeanDefinitionMap到最后的销毁过程. 在Bean的生命中, 管理着它的容器()BeanFactory)提供了Bean的重要生命节点的回调函数.

参考

  • 1.6.1. Lifecycle callbacks
  • Interface BeanFactory

你可能感兴趣的:(Spring,IoC)