1.9、spring源码,bean的生命周期,BeanPostProcessor处理的方法

接1.8、spring源码,bean的生命周期

BeanPostProcessor类[interface]: bean的后置处理器

作用:在bean初始化前后进行一些处理工作

有两个方法

1、postProcessBeforeInitialization():在初始化之前进行后置处理工作(在init-method之前),

什么时候调用:它任何初始化方法调用之前(比如在InitializingBean的afterPropertiesSet初始化之前,或自定义init-method调用之前使用)       

public class Bike {

    public Bike(){
        System.out.println("构造--------bike");
    }
//postProcessBeforeInitialization在这里之前调用
    public void init(){
        System.out.println("init-------bike");
    }
//postProcessAfterInitialization在init之后调用
    public void destory(){
        System.out.println("destory-------bike");
    }
}


@Configuration
public class DemoConfig {

    @Bean(initMethod = "init",destroyMethod = "destory")
    public Bike bike(){
        return new Bike();
    }
}

2、postProcessAfterInitialization():在初始化之后进行后置处理工作, 比如在InitializingBean的afterPropertiesSet()

实例配合上面的bean和config

@Component
public class HonryBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("HonryBeanPostProcessor====postProcessBeforeInitialization");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("HonryBeanPostProcessor====postProcessAfterInitialization");
        return null;
    }
}

执行结果

构造--------bike
HonryBeanPostProcessor====postProcessBeforeInitialization
init-------bike
HonryBeanPostProcessor====postProcessAfterInitialization
IOC容器初始化完成

 

你可能感兴趣的:(Spring源码学习)