`

spring Lifecycle接口

阅读更多
1.初始化回调
实现org.springframework.beans.factory.InitializingBean接口允许容器在设置好bean的所有必要属性后,执行初始化事宜。InitializingBean接口仅指定了一个方法:
void afterPropertiesSet() throws Exception;

通常,要避免使用InitializingBean接口(而且不鼓励使用该接口,因为这样会将代码和Spring耦合起来)可以在Bean定义中指定一个普通的初始化方法,即在XML配置文件中通过指定init-method属性来完成。如下面的定义所示:
<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耦合在一起。
析构回调
实现org.springframework.beans.factory.DisposableBean接口的bean允许在容器销毁该bean的时候获得一次回调。DisposableBean接口也只规定了一个方法:
void destroy() throws Exception;

通常,要避免使用DisposableBean标志接口(而且不鼓励使用该接口,因为这样会将代码与Spring耦合在一起)可以在bean定义中指定一个普通的析构方法,即在XML配置文件中通过指定destroy-method属性来完成。如下面的定义所示:
<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>

public class ExampleBean {

    public void cleanup() {
        // do some destruction work (like releasing pooled connections)
    }
}

(效果)与下面完全一样
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>

public class AnotherExampleBean implements DisposableBean {

    public void destroy() {
        // do some destruction work (like releasing pooled connections)
    }
}

但是没有将代码与Spring耦合在一起。
3.缺省的初始化和析构方法
如果有人没有采用Spring所指定的InitializingBean和DisposableBean回调接口来编写初始化和析构方法回调,而且团队约到使用init(), initialize(),dispose()作为生命周期回调方法的名称,有了前面的约定,就可以将Spring容器配置成在每个bean上查找事先指定好的初始化和析构回调方法名称,这样就可以简化bean定义,比如根据约定将初始化回调命名为init(),我们举例如下:
public class DefaultBlogService implements BlogService {

    private BlogDao blogDao;

    public void setBlogDao(BlogDao blogDao) {
        this.blogDao = blogDao;
    }

    // this is (unsurprisingly) the initialization callback method
    public void init() {
        if (this.blogDao == null) {
            throw new IllegalStateException("The [blogDao] property must be set.");
        }
    }
}

为上述类所添加的XML配置,如下所示:
<beans default-init-method="init">

    <bean id="blogService" class="com.foo.DefaultBlogService">
        <property name="blogDao" ref="blogDao" />
    </bean>

</beans>

该属性的出现意味着Spring IoC容器会把bean上名为'init'的方法识别为初始化方法回调,并且当bean被创建和装配的时候,如果bean类具有这样的方法,它将会在适当的时候被调用,类似的,配置析构方法回调是在顶层<beans/>元素上使用'default-destroy-method'属性。使用该特性可以使你免于在每个bean上指定初始化和析构方法回调的琐碎工作,同时它很好的强化了针对初始化和析构方法回调的命名约定的一致性(一致性是一种应该时常追求的东西)。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics