Bean的生命周期在整个Spring体系都是非常重要的,必须谨记于心。
BeanPostProcessor接口比较特殊,一般单独实现该接口。Spring中所有的Bean在使用过程中都会执行BeanPostProcessor接口的postProcessBeforeInitialization()方法和postProcessAfterInitialization()方法。BeanPostProcessor是容器级别的,对所有的Bean有效。
BeanNameAware、BeanFactoryAware等是Bean级别的,对当前类有效。一个Bean可以同时实现这些接口。
项目中如何实践,项目来源:https://gitee.com/bweird/lenosp.git
len-web模块中com.len.config包下有三个类(BeanFactoryImpl实现了BeanFactoryAware接口,BeanName实现了BeanNameAware接口,ZBeanFactory实现了BeanPostProcessor接口;setBeanFactory()方法只会在加载BeanFactoryImpl时被调用,setBeanName()方法只会在加载BeanName时被调用,postProcessBeforeInitialization()方法和postProcessAfterInitialization()方法在所有的Bean被加载时都会被调用):
@Configuration
@Slf4j
public class BeanFactoryImpl implements BeanFactoryAware {
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
log.info("BeanFactoryAware------->" + beanFactory);
}
}
@Configuration
@Slf4j
public class BeanName implements BeanNameAware {
@Override
public void setBeanName(String name) {
log.info("BeanNameAware-------->:" + name);
}
}
@Configuration
@Slf4j
public class ZBeanFactory implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
log.info("对象---" + beanName + "---初始化开始");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
log.info("对象---" + beanName + "---初始化成功");
return bean;
}
}
2018-11-09 14:36:35.863 INFO 15696 --- [main] com.len.config.BeanFactoryImpl : BeanFactoryAware------->
2018-11-09 14:36:35.864 INFO 15696 --- [main] com.len.config.ZBeanFactory : 对象---beanFactoryImpl---初始化开始
2018-11-09 14:36:35.865 INFO 15696 --- [main] com.len.config.ZBeanFactory : 对象---beanFactoryImpl---初始化成功
2018-11-09 14:36:35.870 INFO 15696 --- [main] com.len.config.BeanName : BeanNameAware-------->:beanName
2018-11-09 14:36:35.871 INFO 15696 --- [main] com.len.config.ZBeanFactory : 对象---beanName---初始化开始
2018-11-09 14:36:35.872 INFO 15696 --- [main] com.len.config.ZBeanFactory : 对象---beanName---初始化成功
2018-11-09 14:36:42.116 INFO 15696 --- [ main] com.len.config.ZBeanFactory : 对象---nullChannel---初始化开始
2018-11-09 14:36:42.123 INFO 15696 --- [ main] com.len.config.ZBeanFactory : 对象---nullChannel---初始化成功
2018-11-09 14:36:42.151 INFO 15696 --- [ main] com.len.config.ZBeanFactory : 对象---errorChannel---初始化开始
2018-11-09 14:36:42.185 INFO 15696 --- [ main] com.len.config.ZBeanFactory : 对象---errorChannel---初始化成功