How to invoke spring bean init and destroy methods?
You can define initialization and destroy methods with in the spring bean. You can configure it using init-method, and destroy-method
in the xml based configuration file. These are part of spring bean life cycle. The initialization method will be called immediately after bean
creation, and destroy method will be called before killing the bean instance.
In this page the example class NetworkManager has an init() method which initializes http connection object, and the destroy()
method will be closing the http connection.
package com.java2novice.beans;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetworkManager {
private HttpURLConnection connection;
public void init(){
System.out.println("Inside init() method...");
String url = "http://www.google.com/search?q=java2novice";
URL obj;
try {
obj = new URL(url);
//initialize http connection here
this.connection = (HttpURLConnection) obj.openConnection();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void destroy(){
try{
System.out.println("Inside destroy() method...");
if(this.connection != null) {
connection.disconnect();
}
} catch(Exception ex){
}
}
public void readData(){
try {
int responseCode = this.connection.getResponseCode();
System.out.println("Response code: "+responseCode);
/**
* do your business logic here
*/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
Here is the xml based configuration, the bean tag has configured with init-method and 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-3.0.xsd">
<bean id="netManager" class="com.java2novice.beans.NetworkManager"
init-method="init" destroy-method="destroy" />
</beans>
|
Finally spring bean demo:
package com.java2novice.test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2novice.beans.NetworkManager;
public class SpringDemo {
public static void main(String a[]){
String confFile = "applicationContext.xml";
ConfigurableApplicationContext context
= new ClassPathXmlApplicationContext(confFile);
NetworkManager networkMng = (NetworkManager) context.getBean("netManager");
networkMng.readData();
context.close();
}
}
|
|