Sunday, March 20, 2011

Spring : init-method and destroy-method

In this first example, I’ll show you how the lifecycle of a bean happens within the xml-configfile.

In the xml-file, we can define an init- and destroy-method to the bean, which will be called automatically by Spring.
Config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
>
<!-- -->
<bean id="attributesTest" class="a.Test" init-method="initMethod"
destroy-method="destroyMethod">
</bean>

</beans>

 

Now consider our bean with these 2 methods into it:

 

public class LifeCycledBean2{    
//
public LifeCycledBean2(){
System.out.println("We are in the constructor of LifeCycledBean2");
}
public void initMethod()
{
System.out.println("We are in initMethod of LifeCycledBean2");
}
public void destroyMethod()
{
System.out.println("We are in destroyMethod of Test");
}
}




Main or Runner program
In this case, I’ll use AbstractApplicationContext because this Context has a function to destroy the Context which a normal ApplicationContext doesn’t have.

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class JustATest {
public static void main(String[] args) {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("Config.xml");
ctx.registerShutdownHook();
Test test = ctx.getBean("attributesTest",Test.class);
}
}


The output will be:

We are in the constructor of Test
We are in initMethod of Test
We are in destroyMethod of Test

It’s also possible to declare default init- and destroy-methods in the xml-file. This is done in the beans-tag:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"

default-init-method="initMethod"
default-destroy-method="destroyMethod"
>
...

No comments:

Post a Comment

Chitika