Spring Bean 的作用范围及生命周期
scope 定义 Bean 的作用范围
- singleton(默认值):单例模式的 bean 对象生命周期与容器相同
对象出生:当创建容器时,对象就被创建了
对象活着:只要容器在,对象一直活着
对象死亡:当销毁容器时,对象就被销毁了 - prototype:多例模式的 bean 对象,spring 框架只负责创建,不负责销毁
对象出生:当使用对象时,创建新的对象实例
对象活着:只要对象在使用中,就一直活着
对象死亡:当对象⻓时间不用时,被 Java 的垃圾回收器回收了
Spring Bean 的生命周期

测试一下效果
1 |
|
1 | public class Result implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean { |
1 |
|
输出:
- 注册我成为bean时定义的id:lazyResult
- 管理我的beanFactory为org.springframework.beans.factory.support.DefaultListableBeanFactory@1d9b7cce: defining beans [jdbcAccountDaoImpl,transactionProxyFactory,myBeanPostProcessor,transferServiceImpl,connectionUtils,transactionManager,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,org.springframework.context.support.PropertySourcesPlaceholderConfigurer#0,dataSource,lazyResult]; root of factory hierarchy
- 高级容器接口ApplicationContext:org.springframework.context.support.ClassPathXmlApplicationContext@5b464ce8, started on Mon May 30 11:26:32 CST 2022
- MyBeanPostProcessor before 方法拦截处理lazyResult
- postConstruct……..
- afterPropertiesSet……..
- initMethod……..
- MyBeanPostProcessor after 方法拦截处理lazyResult
- Result{status=’s’, message=’123’}
- PreDestroy……
- destroy……
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 实现一个小目标!











