您的位置:首页 > 编程语言 > Java开发

如果监控Spring Bean生命周期

2007-04-06 10:18 459 查看
对于singleton bean,Spring容器知道bean何时实例化结束,何时销毁,Spring可以管理实例化结束之后,和销毁之前的行为,管理bean的生命周期行为主要未如下两个时机:

Bean全部依赖注入之后
Bean即将销毁之前

(1)依赖关系注入后的行为实现:
有两种方法:A.编写init方法 B.实现InitializingBean接口

afterPropertiesSet和init同时出现,前者先于后者执行,使用init方法,需要对配置文件加入init-method属性




public void init()...{


System.out.println("in init");


}






public void afterPropertiesSet() throws Exception ...{


System.out.println("in afterPropertiesSet");




}


<bean id="chinese" class="Bean.lifecycle.Chinese" init-method="init" destroy-method="close">


<property name="axe">


<ref local="axe"/>


</property>


</bean>

(2)bean销毁之前的行为

有两种方法:A.编写close方法 B.实现DisposableBean接口

destroy和close同时出现,前者先于后者执行,使用close方法,需要对配置文件加入destroy-method属性




public void close()...{


System.out.println("in close");


}




public void destroy() throws Exception ...{


System.out.println("in destroy");




}


<bean id="chinese" class="Bean.lifecycle.Chinese" init-method="init" destroy-method="close">


<property name="axe">


<ref local="axe"/>


</property>


</bean>

如果需要在bean创建之时和创建之后进行监控,则需要实现BeanPostProcessor接口

其中有两个方法:postProcessBeforeInitialization和postProcessAfterInitialization

这两个方法和init方法的顺序是:postProcessBeforeInitialization-->init-->postProcessAfterInitialization
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: