Spring 简明教程
Spring - Bean Life Cycle
Spring Bean 的生命周期很容易理解。当实例化一个 Bean 时,可能需要执行一些初始化操作使其进入可用状态。同样,当不再需要 Bean 并从容器中移除时,可能需要进行一些清理操作。
The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required.
尽管在 Bean 实例化和销毁之间的时间里有许多幕后活动列表,但本章只讨论两个重要的 Bean 生命周期回调方法,它们在 Bean 初始化和销毁时需要。
Though, there are lists of the activities that take place behind the scene between the time of bean Instantiation and its destruction, this chapter will discuss only two important bean life cycle callback methods, which are required at the time of bean initialization and its destruction.
要为 Bean 定义设置和拆除操作,我们只需使用 initmethod 和/或 destroy-method 参数声明 <bean>。init-method 属性指定一个方法,该方法在实例化后立即在 Bean 上调用。类似地,destroymethod 指定一个方法,该方法在 bean 从容器中移除之前调用。
To define setup and teardown for a bean, we simply declare the <bean> with initmethod and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroymethod specifies a method that is called just before a bean is removed from the container.
Initialization callbacks
org.springframework.beans.factory.InitializingBean 接口指定一个单一的方法 −
The org.springframework.beans.factory.InitializingBean interface specifies a single method −
void afterPropertiesSet() throws Exception;
因此,你可以简单地实现上述接口,初始化工作可以在 afterPropertiesSet() 方法中完成如下:
Thus, you can simply implement the above interface and initialization work can be done inside afterPropertiesSet() method as follows −
public class ExampleBean implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}
}
在基于 XML 的配置文件元数据的情况下,你可以使用 init-method 属性指定具有 void 无参数签名的该方法的名称。例如 −
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. For example −
<bean id = "exampleBean" class = "examples.ExampleBean" init-method = "init"/>
下面的类定义 −
Following is the class definition −
public class ExampleBean {
public void init() {
// do some initialization work
}
}
Destruction callbacks
org.springframework.beans.factory.DisposableBean 接口指定一个单一的方法 −
The org.springframework.beans.factory.DisposableBean interface specifies a single method −
void destroy() throws Exception;
因此,你可以简单地实现上述接口,最终化工作可以在 destroy() 方法中完成如下:
Thus, you can simply implement the above interface and finalization work can be done inside destroy() method as follows −
public class ExampleBean implements DisposableBean {
public void destroy() {
// do some destruction work
}
}
在基于 XML 的配置文件元数据的情况下,你可以使用 destroy-method 属性指定具有 void 无参数签名的该方法的名称。例如 −
In the case of XML-based configuration metadata, you can use the destroy-method attribute to specify the name of the method that has a void no-argument signature. For example −
<bean id = "exampleBean" class = "examples.ExampleBean" destroy-method = "destroy"/>
下面的类定义 −
Following is the class definition −
public class ExampleBean {
public void destroy() {
// do some destruction work
}
}
如果你在一个非网络应用程序环境中使用 Spring 的 IoC 容器,例如在富客户端桌面环境中,你要向 JVM 注册一个关闭钩子。这样做可确保正常关闭,并在你的单例 Bean 上调用相关的销毁方法,以便释放所有资源。
If you are using Spring’s IoC container in a non-web application environment; for example, in a rich client desktop environment, you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your singleton beans so that all resources are released.
建议不要使用 InitializingBean 或 DisposableBean 回调,因为 XML 配置在方法命名方面提供了很大的灵活性。
It is recommended that you do not use the InitializingBean or DisposableBean callbacks, because XML configuration gives much flexibility in terms of naming your method.
Example
让我们准备一个可用的 Eclipse IDE,然后执行以下步骤来创建一个 Spring 应用程序−
Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −
Steps |
Description |
1 |
Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project. |
2 |
Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. |
3 |
Create Java classes HelloWorld and MainApp under the com.tutorialspoint package. |
4 |
Create Beans configuration file Beans.xml under the src folder. |
5 |
The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below. |
以下是 HelloWorld.java 文件的内容 −
Here is the content of HelloWorld.java file −
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
public void init(){
System.out.println("Bean is going through init.");
}
public void destroy() {
System.out.println("Bean will destroy now.");
}
}
以下是 MainApp.java 文件的内容。这里你需要注册一个关闭钩子 registerShutdownHook() 方法,该方法在 AbstractApplicationContext 类中声明。这将确保正常关闭并调用相关的销毁方法。
Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensure a graceful shutdown and call the relevant destroy methods.
package com.tutorialspoint;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
context.registerShutdownHook();
}
}
以下是 init 方法和 destroy 方法所需的配置文件 Beans.xml −
Following is the configuration file Beans.xml required for init and destroy methods −
<?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">
<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" init-method = "init"
destroy-method = "destroy">
<property name = "message" value = "Hello World!"/>
</bean>
</beans>
完成源文件和 Bean 配置文件创建后,我们运行该应用程序。如果您的应用程序一切正常,它将打印以下消息−
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −
Bean is going through init.
Your Message : Hello World!
Bean will destroy now.
Default initialization and destroy methods
如果你有太多具有相同名称的初始化和/或销毁方法的 Bean,则无需在每个单独 Bean 上声明 init-method 和 destroy-method 。相反,框架提供了使用 <beans> 元素上的 default-init-method 和 default-destroy-method 属性配置这种情况的灵活性,如下所示 −
If you have too many beans having initialization and/or destroy methods with the same name, you don’t need to declare init-method and destroy-method on each individual bean. Instead, the framework provides the flexibility to configure such situation using default-init-method and default-destroy-method attributes on the <beans> element as follows −
<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"
default-init-method = "init"
default-destroy-method = "destroy">
<bean id = "..." class = "...">
<!-- collaborators and configuration for this bean go here -->
</bean>
</beans>