@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof UserComponent) {
System.out.println("BeanPostProcessor 开始执行 初始化前..." + beanName);
UserComponent userComponent = (UserComponent) bean;
userComponent.setUserName("liuzhihang-postProcessBeforeInitialization");
return userComponent;
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof UserComponent) {
System.out.println("BeanPostProcessor 开始执行 初始化后..." + beanName);
UserComponent userComponent = (UserComponent) bean;
userComponent.setUserName("liuzhihang-postProcessAfterInitialization");
return userComponent;
}
return bean;
}
}
@Component
public class TestBean implements BeanNameAware {
@Override
public void setBeanName(String s) {
System.out.println(s);
}
}
@Component
public class TestBean implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
@Component
public class A1Service{
@PostConstruct
public void init(){
System.out.println("初始化之后回调。。。");
}
}
@Component
public class A3Service implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("自定义初始化。。。");
}
}
public class Bean2 {
public void init(){
System.out.println("userService 的自定义初始化方法");
}
}
@ComponentScan
public class SpringConfig {
@Bean(initMethod = "init")
public Bean2 getUserServie(){
return new Bean2();
}
}
public class A2Service{
public void init(){
System.out.println("自定义初始化。。。");
}
}
源码
如果bean 实现了 InitializingBean 接口,就执行重写的方法
@Component
public class TestBean implements BeanPostProcessor {
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}