spring bean 生命周期回调

43 篇文章 0 订阅
18 篇文章 0 订阅

                           spring bean 生命周期回调

spring bean的生命周期回调有两种:初始化回调(init-method) 销毁回调(destory-method)

实现生命周期回调有三种方法:实现接口、xml配置、使用注解

初始化生命周期回调(init-method)实现:

  1. 实现org.springframework.beans.factory.InitializingBean接口,eg
public class AnotherExampleBean implements InitializingBean {

    public void afterPropertiesSet() {
        // do some initialization work
    }
}
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>

   2、xml配置init-method

   

public class ExampleBean {

    public void init() {
        // do some initialization work
    }
}
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>

3、使用注解

使用JSP-250规范中的注解@PostConstruct

public class ExampleBean {
@PostConstruct
public void customer_init() {
System.out.println("@PostConstruct注解指定的初始化方法:customer_init。" );
}

}

使用java config注解

@Bean(initMethod = "customer_init")
public User user() {
     ...
}

生命周期销毁回调(destory-method)

实现org.springframework.beans.factory.DisposableBean接口

public class AnotherExampleBean implements DisposableBean {

    public void destroy() {
        // do some destruction work (like releasing pooled connections)
    }
}
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>

使用xml注解,配置destory-method元素

public class ExampleBean {

    public void cleanup() {
        // do some destruction work (like releasing pooled connections)
    }
}
<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>

使用注解

JSR-250注解的方式

public class User {
@PreDestory
    public void customer_destory() {
        System.out.println("调用destory-method指定的初始化方法:customer_destory。" );
    }
}

使用java Config,要在@Bean注解中使用initMehtod属性

@Bean( destroyMethod = "customer_destory")
public User user() {
     ...
}

全局设置

在顶级元素中定义初使化和销毁函数(必须统一函数名)

<beans default-init-method="customer_init" default-destroy-method="customer_destory">
    <bean id="CristianoRonaldo"  class="twm.spring.LifecycleTest.User" />
</beans>

总结

1、在一个bean中,配置多种生命周期回调机制,会按照下列次序调用:
带@PostConstruct注解的方法 -> InitializingBean回调接口中的afterPropertiesSet()方法 ->自定义的init()方法

2、销毁回调也使用相同的次序
带@PreDestroy注解的方法 -> DisposableBean回调接口中的destroy()方法 ->自定义的destroy()方法

3、不管是通过实现 InitializingBean/DisposableBean 接口,还是通过 <bean> 元素的init-method/destroy-method 属性进行配置,都只能为 Bean 指定一个初始化 / 销毁的方法。但是使用 @PostConstruct 和 @PreDestroy 注释却可以指定多个初始化 / 销毁方法,那些被标注 @PostConstruct 或 @PreDestroy 注释的方法都会在初始化 / 销毁时被执行。

4、不建议使用接口和注解实现方式,因为这会让pojo类与Spring框架紧耦合。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值