Spring BeanPostProcessor最佳实践

2021-03-08  本文已影响0人  单名一个冲

Factory hook that allows for custom modification of new bean instances — for example, checking for marker interfaces or wrapping beans with proxies. Typically, post-processors that populate beans via marker interfaces or the like will implement {@link #postProcessBeforeInitialization}, while post-processors that wrap beans with proxies will normally implement {@link #postProcessAfterInitialization}.

属于Bean的实例化阶段扩展,针对于任何Bean的实例化。
执行时机分别位于InitializingBean's afterPropertiesSet方法或者init-method之前和之后,
此时Bean以及实例化完成,对象属性已经注入。

对实例化Bean做进一步的处理,在扩展时机前后调用,把控好时机扩展就好。
比如做一些注解配置的处理等,其他的博主暂时想不到有好的玩法/(ㄒoㄒ)/~~

/**
 * BeanPostProcessor接口默认实现了postProcessBeforeInitialization和postProcessAfterInitialization两个方法,
 * 作用范围:任何Bean实例化对象
 * 方法执行时机:参照各方法注释
 */
@Component
public class TestBeanPostProcess implements BeanPostProcessor {

    /**
     * Apply this {@code BeanPostProcessor} to the given new bean instance <i>before</i> any bean
     * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
     * or a custom init-method).
     *
     * 执行时机:InitializingBean's afterPropertiesSet方法或者init-method之前执行。
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("BeanPostProcessor-Before: " + beanName);
        return bean;
    }

    /**
     * Apply this {@code BeanPostProcessor} to the given new bean instance <i>after</i> any bean
     * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
     * or a custom init-method).
     * <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).
     *
     * 执行时机:InitializingBean's afterPropertiesSet方法或者init-method之后。
     *
     * 注意:Spring2.0后,FactoryBean也要走这个方法。
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("BeanPostProcessor-After: " + beanName);
        return bean;
    }
}

不仅可以实现BeanPostProcessor扩展,Spring还有一些他的子类也提供了扩展:

更多Spring扩展请查看专题Spring开发笔记

上一篇 下一篇

猜你喜欢

热点阅读