![](/img/trans.png)
[英]Doubts about init and destroy bean method in Spring Bean Life Cycle
[英]Some doubts about Spring bean inizialitazion and destruction
在此期间,我正在研究Spring Framework。
现在,我正在研究Spring Bean的生命周期,尤其是有关bean的inizialitazion广告销毁的内容,请阅读此教程:
http://www.tutorialspoint.com/spring/spring_bean_life_cycle.htm
我已经实现了上一篇文章中提出的示例,但是对此说法有疑问。
在示例中,我只有两个类: HelloWorld.java和MainApp.java
在HelloWorld.java类中,我有两种方法用于bean的inizialitazion: init() (在创建bean之后由框架调用)和bean清理:* destroy() (在bean销毁之前由框架调用)在我的申请结束时)
好的,这很明显,框架在bean生命周期的两个特定时刻自动调用了这两种方法,因为我已经通过init-method和destroy-method属性在应用程序上下文xml文件中将此bean分配给了它:
<bean id="helloWorld"
class="org.andrea.myexample.myInitDestroyExample.HelloWorld"
init-method="init" destroy-method="destroy">
<property name="message" value="Hello World!"/>
</bean>
这对我来说似乎很清楚。
我要理解的问题与上一篇文章的开头有关,实际上它表明要使用inizialization方法,我的bean必须实现InitializingBean接口及其方法的代码: afterPropertiesSet()
为了执行bean清理(在删除之前),我的bean必须实现DisposableBean接口及其方法的代码: destroy()
好的...所以...为什么本文中的内容首先表明我的bean必须实现这些接口,然后在此示例中,不执行此操作,而只是声明XML配置中存在init和destroy方法,并且在没有实现任何接口的类中实现它?
特纳克斯
In the case of XML-based configuration metadata, you can use the init-method attribute to specify the name of the method that has a void no-argument signature
XML定义是实现此类接口的替代方法 。
有几种方法可以使Spring的bean初始化/销毁
1)您可以定义default-init-method / default-destroy-method beans
(根元素xml配置),然后Spring将在其实例化的任何bean中查找这些方法
2)您可以为bean定义单独的init-method / destroy-method
3)您可以实现InitializingBean / DisposableBean接口,即使xml config中未定义init-method / destroy-method,Spring也会调用它们
4)您可以使用@PostConstruct / @PreDestroy注释来注释bean中的方法,并在xml配置中打开<context:annotation-config />
虽然当今这一代人采取快速行动,但其中许多人心态不强,无法实现梦想
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.