简单说说 Spring 中BeanPostProcessor是什么

        BeanPostProcessor是spring框架中的一个接口,其作用是可以在bean的生命周期中插入一些自定义逻辑,比如将ApplicationContext赋值给bean,对bean进行aop增强等。

        在BeanPostProcessor中主要有两个方法,分别是:postProcessBeforeInitialization和postProcessAfterInitialization。

  • postProcessBeforeInitialization:可以在初始化方法之前执行某些处理。
  • postProcessAfterInitialization:可以在初始化方法之后执行某些处理。

举个例子:

在spring中,ApplicationContextAware接口的功能就是基于ApplicationContextAwareProcessor实现的,在执行初始化方法之前,spring会执行前置方法,在前置方法中,有如下实现

@Override
@Nullable
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    //判断是否是需要进行处理,例子中,ApplicationContextAware 也是需要进行处理的
    if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
            bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
            bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){
        return bean;
    }

    AccessControlContext acc = null;

    if (System.getSecurityManager() != null) {
        acc = this.applicationContext.getBeanFactory().getAccessControlContext();
    }

    if (acc != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            invokeAwareInterfaces(bean);
            return null;
        }, acc);
    }
    else {
        //调用aware接口的方法
        invokeAwareInterfaces(bean);
    }

    return bean;
}

private void invokeAwareInterfaces(Object bean) {
    if (bean instanceof EnvironmentAware) {
        ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
    }
    if (bean instanceof EmbeddedValueResolverAware) {
        ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
    }
    if (bean instanceof ResourceLoaderAware) {
        ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
    }
    if (bean instanceof ApplicationEventPublisherAware) {
        ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
    }
    if (bean instanceof MessageSourceAware) {
        ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
    }
    //如果接口继承了ApplicationContextAware
    //那么就调用子类中实现的setApplicationContext方法
    if (bean instanceof ApplicationContextAware) {
        ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
    }
}

从源码中可知,如果我们的类实现了ApplicationContextAware可以获取到applicationContext,原因就在这里。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值