[ Spring ] Bean LifeCycle

本文深入探讨了Spring框架中Bean的生命周期控制机制,包括@PostConstruct和@PreDestory注解、InitializingBean接口和DisposableBean接口,以及标准命名方法init()和destory()的应用。同时,介绍了如何在应用上下文中配置这些机制,并强调了使用CommonAnnotationBeanPostProcessor的必要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Bean Life Cycle (Initialization & Destory)

 

We have 3 ways to control th life-cycle of Bean.

1) @PostConstruct and @PreDestory

2) afterPropertiesSet() from interface InitializingBean

     destory() from interface DisposableBean

3) Standard method naming, init() & destory()

 

 

Above are 3 mechanisms, if applying the mechanisms to one bean with different method names,the sequence would be :

 

INFO [com.vincent.spring.main.LifeCycleBean] - LifeCycleBean Constructor
INFO [com.vincent.spring.main.LifeCycleBean] - postConstruct
INFO [com.vincent.spring.main.LifeCycleBean] - AfterPropertiesSet
INFO [com.vincent.spring.main.LifeCycleBean] - init
 

 

if with same names, will only be excuted once.

 

 

In applicationcontext.xml, should add below:

 

 

<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
 

 

For @PostConstruct & @PreDestory,we need to add the dependency of "javax.annotation" to pom.xml.

 

 

<dependency>
	<groupId>javax.annotation</groupId>
	<artifactId>jsr250-api</artifactId>
	<version>1.0</version>
</dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值