Spring bean destruction callback
We will initialize our resources during spring bean creation. We need to close all the opened resources just before killing the
spring bean, all clean up related code will be part of destroy method. You can achieve this by implementing org.springframework.beans.factory.DisposableBean
interface with in your spring bean. You need to implement destroy() method with in your spring bean and move all of your clean up code with
in destroy() method.
An alternative approach has been given in the previous example How to invoke spring bean init and destory methods?.
package com.java2novice.beans;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class NetworkManager implements InitializingBean, DisposableBean{
private HttpURLConnection connection;
private String urlStr;
public void setUrlStr(String urlStr){
this.urlStr = urlStr;
}
public void afterPropertiesSet(){
System.out.println("Inside init() method...");
URL obj;
try {
obj = new URL(this.urlStr);
//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();
}
}
}
|
Xml based configuration file:
<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">
<property name="urlStr" value="http://www.google.com/search?q=java2novice"/>
</bean>
</beans>
|
Spring bean demo class:
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();
}
}
|
|