Spring BeanPostProcessor 代码实践

发布于:2022-12-21 ⋅ 阅读:(134) ⋅ 点赞:(0)


Bean后置处理器接口,在初始化方法前后执行,允许对新建的Bean实例进行自定义修改,如检查标记接口或者包装为代理类。

源码


package org.springframework.beans.factory.config;

import org.springframework.beans.BeansException;
import org.springframework.lang.Nullable;

public interface BeanPostProcessor {

	/**
	 * 在属性填充完成之后,初始化方法(afterPropertiesSet 或者 @PostConstruct)之前执行。
	 */
	@Nullable
	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	/**
	 * 初始化方法之后之前执行。
	 */
	@Nullable
	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

}

执行时机

在Bean实例创建并完成属性填充之后,调用AbstractAutowireCapableBeanFactoryinitializeBean方法初始化Bean。在初始化前后分别执行了 postProcessBeforeInitializationpostProcessAfterInitialization 方法。
Spring BeanPostProcessor 执行时机

代码实践

新建一个BeanPostProcessor实例

/**
 * 对所有Spring管理的Bean都有效
 * */
@Slf4j
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        log.info("执行 BeanPostProcessor.postProcessBeforeInitialization 方法, beanName=>{}", bean, beanName);
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        log.info("执行 BeanPostProcessor.postProcessAfterInitialization 方法, beanName=>{}", bean, beanName);
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}

新建一个Spring Component类,并实现依赖注入和初始化方法

@Slf4j
@Component
public class BeanPostProcessorDemo implements InitializingBean {

    private AnotherComponent anotherComponent;

    @Autowired
    public void setAnotherComponent(AnotherComponent anotherComponent) {
        log.info("执行依赖注入");
        this.anotherComponent = anotherComponent;
    }

    @PostConstruct
    public void init(){
        log.info("执行 @PostConstruct 标注的方法");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("执行 InitializingBean.afterPropertiesSet 方法");
    }

}

运行结果

执行顺序为:依赖注入 > postProcessBeforeInitialization > @PostConstruct > afterPropertiesSet > postProcessAfterInitialization
Spring BeanPostProcessor
注:BeanPostProcessor默认是会对整个Spring容器中所有的bean进行处理。

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到