spring中bean的生命周期

准确的了解Spring Bean的生命周期是非常必要的。我们通常使用ApplicationContext作为Spring容器。这里,我们讲的也是 ApplicationContext中Bean的生命周期。而实际上BeanFactory也是差不多的,只不过处理器需要手动注册。

1、各种接口方法分类

1、Bean自身的方法  :  这个包括了Bean本身调用的方法和通过配置文件中的init-method和destroy-method指定的方法

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

// 通过<bean>的destroy-method属性指定的初始化方法
public void myDestory() {
    System.out.println("【destroy-method】调用<bean>的destroy-method属性指定的初始化方法");
}

2、Bean级生命周期接口方法  :  这个包括了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean这些接口的方法

  • setBeanName :BeanNameAware接口中的方法
  • setBeanFactory : BeanFactoryAware接口中的方法
  • afterPropertiesSet : InitializingBean接口中的方法
  • destroy :InitializingBean和DiposableBean接口中的方法

3、容器级生命周期接口方法  :  这个包括了InstantiationAwareBeanPostProcessor 和 BeanPostProcessor 这两个接口实现,一般称它们的实现类为“后处理器”。

  • InstantiationAwareBeanPostProcessor 接口本质是BeanPostProcessor的子接口,一般我们继承Spring为其提供的适配器类InstantiationAwareBeanPostProcessorAdapter来使用它
  • BeanPostProcessor接口中的方法如下:
        @Override
        public Object postProcessAfterInitialization(Object arg0, String arg1)
                throws BeansException {
            System.out
            .println("BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!");
            return arg0;
        }
    
        @Override
        public Object postProcessBeforeInitialization(Object arg0, String arg1)
                throws BeansException {
            System.out
            .println("BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!");
            return arg0;
        }
  • InstantiationAwareBeanPostProcessorAdapter接口中的方法如下:
// 接口方法、实例化Bean之前调用
    @Override
    public Object postProcessBeforeInstantiation(Class beanClass,
            String beanName) throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法");
        return null;
    }

    // 接口方法、实例化Bean之后调用
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法");
        return bean;
    }
// 接口方法、设置某个属性时调用
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs,
            PropertyDescriptor[] pds, Object bean, String beanName)
            throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法");
        return pvs;
    }

4、工厂后处理器接口方法  :  这个包括了AspectJWeavingEnabler, ConfigurationClassPostProcessor, CustomAutowireConfigurer等等非常有用的工厂后处理器  接口的方法。工厂后处理器也是容器级的。在应用上下文装配配置文件之后立即调用。

2、生命周期流程图

Spring Bean的完整生命周期从创建Spring容器开始,直到最终Spring容器销毁Bean,这其中包含了一系列关键点。

若容器注册了以上各种接口,程序那么将会按照以上的流程进行。下面将仔细讲解各接口作用。

3、生命周期时序图

posted @ 2020-08-20 15:34  Posion゜  阅读(263)  评论(0编辑  收藏  举报