In spring, you can use Init-method and Destroy-method in Bean profile properties to initialize and destroy certain actions in the bean. This is used to replace the Initializingbean and Disposablebean interfaces. Example here is an example showing you how to use Init-method and 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 is set:" + message);} public void CleanUp () throws Exception { System.out.println ("Spring Container is destroy! Customer clean Up ");}}
File:applicationContext.xml, the Init-method and Destroy-method properties are defined in the bean.
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xsi:schemalocation=" http://www.springframework.org/schema/beanshttp:// 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>
Execute the following program code:
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 closes the application context, frees all resources, and destroys all cached singleton beans.
Output
Init method After properties was Set:i ' M property message[email protected] Spring Container is destroy! Customer Clean Up
The Initit () method is called, after the message property is set, after the Context.close () call, the CleanUp () method is executed, and Init-method and Destroy-methodbean are recommended to be used in the Bena configuration file instead of executing The Initializingbean and Disposablebean interfaces also cause unnecessary coupling code in spring. Download Source Codes –http://pan.baidu.com/s/1hreksq4
Spring Bean Init-method and Destroy-method instances