Bean生命周期

初始化

1、实现org.springframework.beans.factory.InitializingBean接口,覆盖afterPropertiesSet方法。

public class ExampleInitializingBean implements InitializingBean{
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet");
    }
}


2、配置init-method。(该类的bean中加上init-method属性,调用该类的init方法。若类中没有init方法将报错。)

<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init">

public class ExampleBean {
    public void init() {
        System.out.println("start");
    }
}


3、配置全局默认初始化方法

在xml开始的<beans>标签中加入default-init-method属性。需在类中有相应的init方法。若没有,不会报错,但不起效。

<beans xmlns="***" default-init-method="init" default-destroy-method="destroy">


销毁

1、实现org.springframework.beans.factory.DisposableBean接口,覆盖destroy方法。

public class ExampleDisposableBean implements DisposableBean{
    @Override
    public void destroy() throws Exception {
        System.out.println("<span style="font-family: Arial, Helvetica, sans-serif;">destroy</span><span style="font-family: Arial, Helvetica, sans-serif;">");</span>
    }
}


2、配置destroy-method。(该类的bean中加上destroy-method属性,调用该类的cleanup方法。若类中没有cleanup方法将报错。)

<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="<span style="font-family: Arial, Helvetica, sans-serif;">cleanup</span><span style="font-family: Arial, Helvetica, sans-serif;">"></span>

public class ExampleBean {
    public void cleanup() {
        System.out.println("stop");
    }
}


3、配置全局默认销毁方法

在xml开始的<beans>标签中加入default-destroy-method属性。需在类中有相应的destroy方法。若没有,不会报错,但不起效。

<beans xmlns="***" default-init-method="init" default-destroy-method="destroy">


总结:

若同时有默认的初始化/销毁方式和bean中的初始化/销毁方式,则默认方式不起效。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值