谈谈我对SpringBean生命周期的理解-创新互联
前言
Spring的ioc容器功能非常强大,负责Spring的Bean的创建和管理等功能。而Spring 的bean是整个Spring应用中很重要的一部分,了解Spring Bean的生命周期对我们了解整个spring框架会有很大的帮助。
BeanFactory和ApplicationContext是Spring两种很重要的容器,前者提供了最基本的依赖注入的支持,而后者在继承前者的基础进行了功能的拓展,例如增加了事件传播,资源访问和国际化的消息访问等功能。本文主要介绍了ApplicationContext和BeanFactory两种容器的Bean的生命周期。
首先看下生命周期图:
再谈生命周期之前有一点需要先明确:
Spring 只帮我们管理单例模式 Bean 的 完整 生命周期,对于 prototype 的 bean ,Spring 在创建好交给使用者之后则不会再管理后续的生命周期。
注解方式
在 bean 初始化时会经历几个阶段,首先可以使用注解 @PostConstruct , @PreDestroy 来在 bean 的创建和销毁阶段进行调用:
@Component public class AnnotationBean { private final static Logger LOGGER = LoggerFactory.getLogger(AnnotationBean.class); @PostConstruct public void start(){ LOGGER.info("AnnotationBean start"); } @PreDestroy public void destroy(){ LOGGER.info("AnnotationBean destroy"); } }
当前题目:谈谈我对SpringBean生命周期的理解-创新互联
文章源于:http://myzitong.com/article/dghoig.html