先說結論
介面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;
}
}