美文网首页3
Spring BeanPostProcessor 接口

Spring BeanPostProcessor 接口

作者: happyJared | 来源:发表于2019-10-03 09:32 被阅读0次

上篇文章提到的 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"/>

相关文章

网友评论

    本文标题:Spring BeanPostProcessor 接口

    本文链接:https://www.haomeiwen.com/subject/wdwlpctx.html