详解Java的Spring框架中bean的定义以及生命周期
bean的定义 bean定义包含所需要的容器要知道以下称为配置元数据的信息:
上述所有配置元数据转换成一组的下列属性构成每个bean的定义。 Spring配置元数据
我们已经看到了基于XML的配置元数据如何提供给容器,但让我们看到了不同的bean定义,包括延迟初始化,初始化方法和销毁方法基于XML配置文件的另一个示例: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- A simple bean definition --> <bean id="..." class="..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- A bean definition with lazy init set on --> <bean id="..." class="..." lazy-init="true"> <!-- collaborators and configuration for this bean go here --> </bean> <!-- A bean definition with initialization method --> <bean id="..." class="..." init-method="..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- A bean definition with destruction method --> <bean id="..." class="..." destroy-method="..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- more bean definitions go here --> </beans> bean的生命周期 不过,还有把bean背后的实例化和销毁时间之间的场景发生的活动,但是本章将只讨论其中两个是需要在bean的初始化和销毁的时候,重要bean的生命周期回调方法。 要定义安装和拆卸一个bean,我们只是声明了初始化方法和/或销毁,方法的参数<bean>。在init-method属性指定一个方法,是被调用bean后立即实例化。同样,销毁方法规定了被调用当bean被从容器中取出之前的方法。 初始化回调: void afterPropertiesSet() throws Exception; public class ExampleBean implements InitializingBean { public void afterPropertiesSet() { // do some initialization work } } 在基于XML的配置元数据的情况下,可以使用init-method 属性来指定具有void无参数签名的方法的名称。例如: <bean id="exampleBean" class="examples.ExampleBean" init-method="init"/> 下面是类的定义: public class ExampleBean { public void init() { // do some initialization work } } 销毁回调 void destroy() throws Exception; 因此,你可以简单地实现上述接口和定稿工作可以做里面的destroy() 方法,如下所示: public class ExampleBean implements DisposableBean { public void destroy() { // do some destruction work } } 在基于XML的配置元数据的情况下,您可以使用destroy-method属性来指定具有void无参数签名的方法的名称。例如: <bean id="exampleBean" class="examples.ExampleBean" destroy-method="destroy"/> 下面是类的定义: public class ExampleBean { public void destroy() { // do some destruction work } } 如果您在非web应用环境中使用Spring的IoC容器,例如在桌面富客户端环境; 注册关闭钩子在JVM中。这样做可以确保正常关机,并让所有的资源都被释放调用singleton bean上的相关destroy方法。 建议不要使用的InitializingBean或者DisposableBean的回调,因为XML配置提供极大的灵活性在命名你的方法方面。 例如: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |