BeanPostProcessor接口 和 InitializingBean接口
相同点:
- 必须都被spring容器管理(对应注解或xml中配置bean),接口中的方法才会被使用生效;
- 都是在bean实例化过程中调用接口对应的方法;
不同点:
InitializingBean
作用对象:只针对该接口的实现类bean;
BeanPostProcessor
作用对象:spring容器管理的所有bean;或可以在方法中自定义选择特定的bean处理业务逻辑
执行顺序:构造器->postProcessBeforeInitialization->@PostConstruct->afterPropertiesSet()->init-method属性->postProcessAfterInitialization
代码举例:
@Data
@ToString
public class Cart implements InitializingBean {
public Cart() {
System.out.println("构造器");
}
@FieldMapping("ID")
private Integer id;
@FieldMapping("DESC-lq")
private String desc;
@PostConstruct
public void init() {
System.out.println("init:" + this.getId());
}
private void initMethod() {
System.out.println("initMethod:" + this.getId());
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("initializingBean:" + this.getId());
}
}
@Configuration
public class CartConfiguration {
@Bean(initMethod = "initMethod")
public Cart cart() {
return new Cart();
}
}
@Component
public class BeanPostProcessorImpl implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization: " + beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization: " + beanName);
return bean;
}
}