13 Spring Bean init-method 和 destroy-method实例

在Spring中,可以使用 init-method 和 destroy-method 在bean 配置文件属性用于在bean初始化和销毁某些动作时。这是用来替代 InitializingBean和DisposableBean接口。

示例

这里有一个例子向您展示如何使用 init-method 和 destroy-method。

实体类
package com.gp6.initAndDestory;

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");
    }
}

配置文件, 在bean中定义了init-method和destroy-method属性。


    
        
        
    
        

执行文件
package com.gp6.initAndDestory;

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

public class InitAndDestory {
     public static void main( String[] args ) {
            
         ConfigurableApplicationContext context = 
                    new ClassPathXmlApplicationContext(new String[] {"com/gp6/initAndDestory/InitAndDestory.xml"});

        CustomerService cust = (CustomerService)context.getBean("customerService");
            
        System.out.println(cust);
            
        context.close();
    }
}

输出
Init method after properties are set =====: i'm property message
com.gp6.initAndDestory.CustomerService@69267649
Spring Container is destroy! Customer clean up

initIt()方法被调用,消息属性设置后,在 context.close()调用后,执行 cleanUp()方法;
建议使用init-method 和 destroy-methodbean 在Bena配置文件,而不是执行 InitializingBean 和 DisposableBean 接口,也会造成不必要的耦合代码在Spring。

你可能感兴趣的:(13 Spring Bean init-method 和 destroy-method实例)