• 欢迎光临~

后置处理器BeanPostProcessor

开发技术 开发技术 2022-10-05 次浏览

BeanPostProcessor:回调机制,在 bean 的初始化前后做一些额外的处理,扩展功能。
可以配置多个 BeanPostProcessor 实例,并且可以通过实现Ordered接口,设置order属性来控制这些BeanPostProcessor实例的运行顺序。

//原接口
public interface BeanPostProcessor {
    
    default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

//编写后置处理器,对每个bean的创建都会生效
@Component
public class AnimalBeanPostProcessor implements BeanPostProcessor {
    
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("拦截到Bean的初始化之前:" + beanName);
        return bean;
    }
    
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("拦截到Bean的初始化之后:" + beanName);
        return bean;
    }
}

通过后置处理器修改bean的属性

@Component
public class CatBeanPostProcessor implements BeanPostProcessor {
    
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Cat) {
            Cat cat = (Cat) bean;
            System.out.println("初始化之前,cat的name为:" + cat.getName());
            cat.setName("zhangsan");
        }
        return bean;
    }
    
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Cat) {
            Cat cat = (Cat) bean;
            System.out.println("初始化之后,cat的name为:" + cat.getName());
        }
        return bean;
    }
}

bean的初始化流程:
后置处理器BeanPostProcessor
对于factorybean,后置处理器会在factorybean创建时执行Before和after方法,在用factorybean去getbean时,执行after方法。

程序员灯塔
转载请注明原文链接:后置处理器BeanPostProcessor
喜欢 (0)
违法和不良信息举报电话:022-22558618 举报邮箱:dljd@tidljd.com