Spring学习(十二)-----Spring Bean init-method 和 destroy-method实例

实现 初始化方法和销毁方法3种方式:
  1. 实现标识接口 InitializingBean,DisposableBean(不推荐使用,耦合性太高)
  2. 设置bean属性 Init-method destroy-method
  3. 使用注释配置后,调用@PostConstruct和@PreDestroy注解
 
在Spring中,可以使用 init-method 和 destroy-method 在bean 配置文件属性用于在bean初始化和销毁某些动作时。这是用来替代 InitializingBean和DisposableBean接口
  • 对于init-method方法,它将运行 afterPropertiesSet()在所有的 bean 属性被设置之后。
  • 对于destroy-method方法,它将运行 destroy()在 Spring 容器释放该 bean 之后。

示例

这里有一个例子向您展示如何使用 init-method 和 destroy-method。
package com.yiibai.customer.services;

public class CustomerService
{
    String message;
    
    public String getMessage() {
      return message;
    }

    public void setMessage(String message) {
      this.message = message;
    }
    
    public void initIt() throws Exception {
      System.out.println("Init method after properties are set : " + message);
    }
    
    public void cleanUp() throws Exception {
      System.out.println("Spring Container is destroy! Customer clean up");
    }
    
}

File : applicationContext.xml, 在bean中定义了init-method和destroy-method属性。

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

    <bean id="customerService" class="com.yiibai.customer.services.CustomerService" 
        init-method="initIt" destroy-method="cleanUp">
           
        <property name="message" value="i'm property message" />
    </bean>
        
</beans>

执行下面的程序代码:

package com.yiibai.common;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.yiibai.customer.services.CustomerService;

public class App 
{
    public static void main( String[] args )
    {
        ConfigurableApplicationContext context = 
        new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});
    
        CustomerService cust = (CustomerService)context.getBean("customerService");
        
        System.out.println(cust);
        
        context.close();
    }
}
ConfigurableApplicationContext.close将关闭应用程序上下文,释放所有资源,并销毁所有缓存的单例bean。


输出

Init method after properties are set : I'm property message
com.yiibai.customer.services.CustomerService@5f49d886 
Spring Container is destroy! Customer clean up
 initIt()方法被调用,消息属性设置后,在 context.close()调用后,执行 cleanUp()方法;
建议使用init-method 和 destroy-methodbean 在Bena配置文件,而不是执行 InitializingBean 和 DisposableBean 接口,也会造成不必要的耦合代码在Spring。
在Spring中,可以使用 init-method 和 destroy-method 在bean 配置文件属性用于在bean初始化和销毁某些动作时。这是用来替代 InitializingBean和DisposableBean接口
 
作者:逆舟
https://www.cnblogs.com/zy-jiayou/
本博客文章均为作者原创,转载请注明作者和原文链接。
原文地址:https://www.cnblogs.com/zy-jiayou/p/7722628.html