天天看点

spring学习(官网)——InitializingBean 和DisposableBean

为了和容器生存周期的管理交互,你可以实现spring的

InitializingBean

DisposableBean

接口,容器为前者回调

afterPropertiesSet

()方法,后者回调

destroy

()方法,允许容器在初始化和销毁bean时执行合适的操作。

JSR-250 @PostConstruct

@PreDestroy

注解通常认为是在现代spring应用接收生存周期回调的最佳实践,使用这些注解意味着bean不和spring特定的接口耦合。

在内部,spring framework使用

BeanPostProcessor

的实现类处理他可以找到的任何回调接口并且调用合适的方法,如果您需要自定义的功能或其他生存周期行为,spring没有提供现成的接口,你可以实现自定义的

BeanPostProcessor

除了初始化和销毁回调外,spring管理的对象也可以实现

Lifecycle

接口,以便这些对象可以参与由容器自身生命周期驱动的启动和关闭过程。

nitialization callbacks

org.springframework.beans.factory.InitializingBean接口允许bean在所有必要的属性被容器设置后执行初始化操作,initializingbean接口指定一个单一的方法:

void afterPropertiesSet() throws Exception;
           

使用

InitializingBean

接口是不被建议的,要不然使用

@PostConstruct

注解(在初始化方法上使用)或者指定一个POJO的初始化方法,在基于xml配置的情况下,使用

init-method

属性指定有一个void,无参数特征的方法名,用java配置,就是使用@bean的

initMethod

属性,比如:

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

    public void init() {
        // do some initialization work
    }

}
           

和以下一样:

<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
           
public class AnotherExampleBean implements InitializingBean {

    public void afterPropertiesSet() {
        // do some initialization work
    }

}
           

但是不和spring耦合。

Destruction callbacks

实现

org.springframework.beans.factory.DisposableBean

接口允许容器被销毁时bean被回调,

DisposableBean

指定一个方法

void destroy() throws Exception;
           

InitializingBean

类似,一般是使用

@PreDestroy

注解或者指定bean定义中通用的方法,基于xml配置是使用bean的

destroy-method

属性,java配置使用

@Bean

initMethod

属性:

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

    public void init() {
        // do some initialization work
    }

}
           

和以下是一样的:

<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
           
public class AnotherExampleBean implements InitializingBean {

    public void afterPropertiesSet() {
        // do some initialization work
    }

}
           

但是不是和spring耦合的代码。