Spring bean initialization callback
Spring comes with different options to call initialization method. In general, we need to initialize some resources during
bean creation. You can achieve this by implementing org.springframework.beans.factory.InitializingBean inteface with in your spring bean.
You need implement afterPropertiesSet() method, and write all initialization code with in this 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.InitializingBean;
public class NetworkManager implements InitializingBean{
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 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();
}
}
|
|