Spring InitializingBean/init-method和DisposableBean/destroy-method

1.initializingBean/init-method
实现org.springframework.beans.factory.InitializingBean接口允许一个bean在它的所有必须属性被BeanFactory设置后,来执行初始化的工作,InitialzingBean仅仅指定了一个方法。
通常InitializingBean接口的使用是能够被避免的,(不鼓励使用,因为没有必要把代码通Spring耦合起来) Bean的定义支持指定一个普通的初始化方法,在使用XmlBeanFactory的情况下,可以通过指定init-method属性来完成

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;


public class ExampleBean implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(ExampleBean.class);
@Override
public void afterPropertiesSet() throws Exception {
logger.info("当实现InitializingBean接口时,执行ExampleBean afterPropertiesSet..........");;
}

public void init() {
logger.info("当xml中配置init-method方法(init)时执行ExampleBean init...........");
}
}


[code]
<bean id="exampleBean" class="com.mx.bean.ExampleBean" init-method="init"></bean>
[/code]
同时实现InitializingBean和xml中配置init-method时,先执行afterPropertiesSet。
输出:
[quote]
[2015-06-24 16:55:43 INFO ] [ContainerBackgroundProcessor[StandardEngine[Catalina]]] (com.mx.bean.ExampleBean.java:12) - 当实现InitializingBean接口时,执行ExampleBean afterPropertiesSet..........
[2015-06-24 16:55:43 INFO ] [ContainerBackgroundProcessor[StandardEngine[Catalina]]] (com.mx.bean.ExampleBean.java:16) - 当xml中配置init-method方法(init)时执行ExampleBean init...........
[/quote]
2.DisposableBean/destroy-method
实现org.springframework.beans.factory.DisposableBean接口允许一个bean.可以再包含它的BeanFactory销毁的时候得到一个回调。DisposableBean也指定了一个方法。

注意:通常DisposableBean接口的使用能够避免的(不鼓励去使用,因为它不必要将代码耦合于spring中) bean的定义支持指定一个普通的析构方法。在使用xmlBeanFactory使用的情况下,它是通过destroy-method属性完成。

重要的提示:当以prototype模式部署一个bean的时候,bean的生命周期将会有少许的变化,通过定义,spring无法管理一个non-singleton/property bean的生命周期,因为当它创建之后,你可以把spring的角色想象成new操作符的替代品。从那之后任何生命周期方面的事情都有客户端来处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值