spring学习总结007 --- IOC容器级生命周期接口
2021-04-23 21:28
标签:throw abstract exce 做了 err return 学习总结 技术 没有 spring提供了两个容器级生命周期接口:InstantiationAwareBeanPostProcessor、BeanPostProcessor(其实BeanFactoryPostProcessor也算是容器级生命周期接口,前面已经介绍过了) 该接口用于在bean实例化前后,以及设置属性前对bean的扩展处理;由于继承了BeanPostProcessor接口,该接口也具备在实例化前后对bean进行扩展的能力 1、postProcessBeforeInstantiation方法执行时机 该方法在bean实例化之前执行,源码中所在的位置如下:AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation 2、postProcessAfterInstantiation执行时机 该方法在bean实例化后,初始化前执行,源码中的位置为:AbstractAutowireCapableBeanFactory.populateBean 同样,postProcessProperties方法也在AbstractAutowireCapableBeanFactory.populateBean方法中 3、示例 运行结果: =================================================================================================== 这里做了件蠢事,spring配置文件里只配置了MyBeanPostProcessor,运行时发现回调方法均未执行;分析了下: 源码中,在注册BeanPostProcessor会进行getBean操作,即创建自定义的bean。由于默认的是单例模式,因此后面再次进行获取就不会再次调用postProcessBeforeInitialization()和postProcessAfterInitialization()方法,因为已经放入了spring缓存,直接获取,不需要实例,因此没有调用。如果你真的想使用的时候调用postProcessBeforeInitialization()和postProcessAfterInitialization()方法,将你的bean设置为原型模式(prototype),这样每次调用都会创建,因此初始化容器之后每次都会调用的。 spring学习总结007 --- IOC容器级生命周期接口 标签:throw abstract exce 做了 err return 学习总结 技术 没有 原文地址:https://www.cnblogs.com/sniffs/p/13268163.html@Slf4j
public class MyBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
@Override
public Object postProcessBeforeInstantiation(Class> beanClass, String beanName) throws BeansException {
log.info("[postProcessBeforeInstantiation] beanClass:{}, beanName:{}", beanClass, beanName);
return null;
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
log.info("[postProcessAfterInstantiation] beanName:{}", beanName);
return true;
}
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
log.info("[postProcessProperties] pvs:{}, beanName:{}", pvs, beanName);
return pvs;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
log.info("[postProcessBeforeInitialization] beanName:{}", beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
log.info("[postProcessAfterInitialization] beanName:{}", beanName);
return bean;
}
}
bean class="com.demo.processor.MyBeanPostProcessor" id="myBeanPostProcessor"/>
bean class="com.demo.bean.Info" id="info">
property name="age" value="28" />
bean>
public class Test4 {
public static void main(String[] args) {
new ClassPathXmlApplicationContext("classpath:bean4.xml");
}
}
文章标题:spring学习总结007 --- IOC容器级生命周期接口
文章链接:http://soscw.com/index.php/essay/78665.html