BeanPostProcessor 接口和@PostConstruct 在使用姿势上差异

先说结论

接口BeanPostProcessor 更灵活,
可以实现bean生命周期里前,后分别执行某些内容,必须是spring管理的bean才能实现此功能,不加@Component不生效

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 在 bean 初始化之前执行逻辑
        if (bean instanceof MyBean) {
            System.out.println("Before Initialization: " + beanName);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 在 bean 初始化之后执行逻辑
        if (bean instanceof MyBean) {
            System.out.println("After Initialization: " + beanName);
        }
        return bean;
    }
}
posted @ 2024-07-29 16:28  SpecialSpeculator  阅读(11)  评论(0编辑  收藏  举报