Spring学习笔记3

当一个bean被实例化时,它可能需要执行一些初始化使它转换成可用状态。

当bean不再需要,并且从容器中移除是,可能需要做一些清除工作。

为了定义安装和拆卸一个bean,我们只要声明带有init-method和/或destroy-method参数

init-method属性指定一个方法,在实例化bean时,立即调用该方法。

destroy-method指定一个方法,只有从容器中移除bean之后,才能调用该方法。

示例:

beans.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.xsd">

    <bean id="helloWorld" class="com.microyum.HelloWorld" init-method="init" destroy-method="destroy">
        <property name="message" value="Hello World" />
    </bean>
</beans>

 

HelloWorld.java

 1 public class HelloWorld {
 2     private String message;
 3 
 4     public void getMessage() {
 5         System.out.println("Your Message : " + message);
 6     }
 7 
 8     public void setMessage(String message) {
 9         this.message = message;
10     }
11 
12     public void init() {
13         System.out.println("Bean is going through init.");
14     }
15 
16     public void destroy() {
17         System.out.println("Bean will destroy now.");
18     }
19 
20 }
View Code

MainApp.java

 1 import org.springframework.context.support.AbstractApplicationContext;
 2 import org.springframework.context.support.ClassPathXmlApplicationContext;
 3 
 4 public class MainApp {
 5     public static void main(String[] args) {
 6         AbstractApplicationContext context = new ClassPathXmlApplicationContext(
 7                 "beans.xml");
 8         HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
 9         
10         obj.getMessage();
11         context.registerShutdownHook();
12     }
13 }
View Code

MainApp.java文件里,需要注册一个在AbstractApplicationContext类中声明的关闭hook的registerShutdownHook()方法。它将确保正常关闭,并且调用相关的destroy方法。

输出信息:

Bean is going through init.
Your Message : Hello World
Bean will destroy now.

如果有太多具有相同名称的初始化或者销毁方法的Bean,那么不需要在每一个bean上声明初始化方法和销毁方法。

框架使用元素中的default-init-method和default-destroy-method属性提供了灵活地配置这种情况。

<?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.xsd"
    default-init-method="init"
    default-destroy-method="destroy">

    <bean id="helloWorld" class="com.microyum.HelloWorld">
        <property name="message" value="Hello World" />
    </bean>
</beans>

原文地址:https://www.cnblogs.com/microyum/p/6879749.html