Spring BeanPostProcessor 接口

上篇文章提到的 Spring Aware 接口,是针对某个实现这些接口的 Bean 定制初始化的过程,不过 Spring 同样可以针对容器中的所有 Bean,或者某些 Bean 的定制初始化过程,这只需提供一个实现 BeanPostProcessor 接口的类即可。

该接口中包含两个方法,postProcessBeforeInitialization 和 postProcessAfterInitialization,其中:

  • postProcessBeforeInitialization 方法会在容器中的 Bean 初始化之前执行
  • postProcessAfterInitialization 方法在容器中的 Bean 初始化之后执行

例子如下:

public class CustomerBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("执行 BeanPostProcessor 的 postProcessBeforeInitialization 方法, beanName=" + beanName);
        return bean;
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("执行 BeanPostProcessor 的 postProcessAfterInitialization 方法, beanName=" + beanName);
        return bean;
    }
}

如果要将 BeanPostProcessor 的 Bean 像其他 Bean 一样定义在 xml 配置文件中,可以这么定义:

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