spring bean的生命周期

本文介绍了Spring框架中Bean的生命周期管理的三种方式:通过配置init-method和destroy-method;实现InitializingBean和DisposableBean接口;以及在beans标签中配置默认的初始化和销毁方法。

bean 的生命周期有三种实现的方式

第一种

是在bean中作如下配置 并且在HelloServiceIml 中添加init和destroy方法

<bean id="helloService" class="com.meng.test.HelloServiceIml" init-method="init" destroy-method="destroy" ></bean>

注意:如果HelloServiceIml中没有init和destroy方法则会报错

public class HelloServiceIml implements HelloService {
public void init() {
System.out.println(" init.....");

}
public void destroy() {
System.out.println("destroy.....");
}

}

第二种是让HelloServiceIml实现InitializingBean,DisposableBean这两个接口 并且实现里边的方法 afterPropertiesSet() destroy() 此时

<bean id="helloService" class="com.meng.test.HelloServiceIml" ></bean>别配nit-method="" destroy-method="" 

public class HelloServiceIml implements HelloService,InitializingBean,DisposableBean {
public void sayHello() {
System.out.println("hello world");
}

//这个是InitializingBean中接口方法的实现
public void afterPropertiesSet() throws Exception {
System.out.println("init........");

}

//这个是DisposableBean 中接口方法的实现
public void destroy() throws Exception {
System.out.println("destroy........");
}

}

第三种是在<beans>中进行default-init-method="init" default-destroy-method="destroy" 配置 这种和第一种很相似 只不过是这种是批量的 就是该xml下的bean

中的类如果有init和destroy方法 就都会执行 没有就不会执行 不匹配 也不会报错 就是一个可选的选项

<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"

default-init-method="init" default-destroy-method="destroy">

总结:如果有第一种存在时就会覆盖第三种 也就是说当第一种存在时第三种就不会执行 尽管匹配也不会执行 第二种不与其他两种发生冲突

---------------------------------------------------------------------------------------------------------

自己总结的 有不太懂的 就看看吧 有不对的地方请大家指出 便不甚感激 

转载于:https://www.cnblogs.com/mengfanyao/p/4491998.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值