Use of init-method and destroy-method attributes in bean
definition
Spring container can be configured to look for these initialization and destroy callback method names on the bean. In order to do so, it needs to find the init-method and destroy-method elements inside the bean definition. Thus, the named callback methods will be invoked.The HelloWorld bean now has two methods, initIt() and cleanUp() that print a message.
<bean id="messanger"
class="com.bean.HelloWorld" init-method="initIt" destroy-method="cleanUp">
<property name="msg"
value="Hello World" />
</bean>
Bean Definition
public class HelloWorld implements BeanPostProcessor{
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public Object postProcessBeforeInitialization(Object
bean, String beanName)
throws BeansException {
System.out.println("BeforeInitialization
: "
+ beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object
bean, String beanName)
throws BeansException {
System.out.println("ProcessAfterInitialization
: "
+ beanName);
return bean;
}
public void initIt() {
System.out.println("Bean is going
through init.");
}
public void cleanUp() {
System.out.println("Bean will
destroy now.");
}
}
public class HelloMain {
public static void main(String[] args) {
AbstractApplicationContext
context = new
ClassPathXmlApplicationContext("spring-beans.xml");
HelloWorld
obj = (HelloWorld) context.getBean("messanger");
System.out.println(obj.getMsg());
context.registerShutdownHook();
}
}
output
Jun 07, 2014 12:05:15 AM
org.springframework.context.support.ClassPathXmlApplicationContext
prepareRefresh
INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext@75cfa3d2:
startup date [Sat Jun 07 00:05:15 IST 2014]; root of context hierarchy
Jun 07, 2014 12:05:15 AM
org.springframework.beans.factory.xml.XmlBeanDefinitionReader
loadBeanDefinitions
INFO: Loading XML bean definitions from
class path resource [spring-beans.xml]
Bean is going through init.
BeforeInitialization : test
ProcessAfterInitialization : test
Hello World
Bean will destroy now.
Another easy way for initialization and destroy method callbacks without the use of Spring-specific InitializingBean andDisposableBean callback interfaces
public class
HelloWorldBeanPostProcessor implements InitializingBean,DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("Bean will
destroy now.");
}
@Override
public void afterPropertiesSet()
throws Exception {
System.out.println("Bean is going
through init.");
}
}
0 comments: