Spring Bean生命周期(四) BeanPostProcessor后置处理器

BeanPostProcessor 源码如下:

public interface BeanPostProcessor {

    /**
     * Apply this BeanPostProcessor to the given new bean instance <i>before</i> any bean
     * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
     * or a custom init-method). The bean will already be populated with property values.
     * The returned bean instance may be a wrapper around the original.
     * <p>The default implementation returns the given {@code bean} as-is.
     * @param bean the new bean instance
     * @param beanName the name of the bean
     * @return the bean instance to use, either the original or a wrapped one;
     */
    @Nullable
    default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * Apply this BeanPostProcessor to the given new bean instance <i>after</i> any bean
     * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
     * or a custom init-method). The bean will already be populated with property values.
     * The returned bean instance may be a wrapper around the original.
     * <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
     * instance and the objects created by the FactoryBean (as of Spring 2.0). The
     * post-processor can decide whether to apply to either the FactoryBean or created
     * objects or both through corresponding {@code bean instanceof FactoryBean} checks.
     * <p>This callback will also be invoked after a short-circuiting triggered by a
     * {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
     * in contrast to all other BeanPostProcessor callbacks.
     * <p>The default implementation returns the given {@code bean} as-is.
     * @param bean the new bean instance
     * @param beanName the name of the bean
     * @return the bean instance to use, either the original or a wrapped one; 
     */
    @Nullable
    default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

}

下面开始写代码证实后置处理器执行的时机

Cat、Car、Dog三个类采用了三种带有初始化的方法,car 的init 和destroy 需要 @Bean 注解去指定

public class Car {
    public void init() {
        System.out.println("=======初始化一个car");
    }
    public void destroy() {
        System.out.println("=======销毁一个car");
    }
}
@Component
public class Cat implements InitializingBean, DisposableBean {
    public Cat() {
        System.out.println("========cat constructor");
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("========Cat 执行 afterPropertiesSet");
    }
    @Override
    public void destroy() throws Exception {
        System.out.println("========Cat 执行 destroy");
    }
}
@Component
public class Dog {
    public Dog() {
        System.out.println("=======dog constructor ");
    }
    //对象创建并赋值之后进行调用
    @PostConstruct
    public void init() {
        System.out.println("========Dog对象初始化");
    }
    @PreDestroy
    public void destroy() {
        System.out.println("========Dog对象销毁");
    }
}

创建自定义后置处理器

/**
 * 初始化前后进行处理
 * 将后置处理器加入容器当中
 */
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization========="+beanName);
        return bean;
    }

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

配置类

@Configuration
@ComponentScan("com.funtl.hello.spring.cloud.eureka.postprocessor")
public class MainConfigOfLifeCycle {
    @Scope("prototype")
    @Bean(initMethod = "init",destroyMethod = "destroy")
    public Car car() {
        return new Car();
    }
}

启动类

public class IocTestLifeCycle {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
        //printBeans(applicationContext);
        applicationContext.getBean("car");
        applicationContext.close();

    }

输出结果:

postProcessBeforeInitialization=========org.springframework.context.event.internalEventListenerProcessor
postProcessAfterInitialization==========org.springframework.context.event.internalEventListenerProcessor
postProcessBeforeInitialization=========org.springframework.context.event.internalEventListenerFactory
postProcessAfterInitialization==========org.springframework.context.event.internalEventListenerFactory
postProcessBeforeInitialization=========mainConfigOfLifeCycle
postProcessAfterInitialization==========mainConfigOfLifeCycle
===========cat constructor
postProcessBeforeInitialization=========cat
==========Cat 执行 afterPropertiesSet
postProcessAfterInitialization==========cat
===========dog constructor 
postProcessBeforeInitialization=========dog
============Dog对象初始化
postProcessAfterInitialization==========dog 
postProcessBeforeInitialization=========car 
==========初始化一个car
postProcessAfterInitialization==========car 
Dog对象销毁 
===========Cat 执行 destroy

很明显postProcessBeforeInitialization在初始化方法前执行,postProcessAfterInitialization在初始化方法后执行

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。