Wednesday, May 25, 2011

init-method and destroy-method attribute in Spring

Sometimes it required to call a (non-static) method in the bean only-once at the ApplicationContext load up, just to initialize the bean components. So you may inject some parameters by setters or constructors, but than you may have some other fields, which have to instantiated from those fields or separately like from some local file.

So for this various approaches are available. See here for these approaches.

Consider the Student service example we saw here. Also note the approach of doing the same thing by using @PostConstruct and @PreDestroy annotations.

Service Bean:

public class StudentService {

String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}


public void initIt() throws Exception {
System.out.println("After properties has been set : " + message);
//do some initialization
}


public void cleanUp() throws Exception {
System.out.println("Cleaned Everyting");
}

}


Bean config file (initMethod.xml):

<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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd"
>
<!-- our bean here -->
<bean id="studentService" class="com.xxxx.StudentService"
init-method="initIt" destroy-method="cleanUp">
<property name="message" value="property message" />
</bean>

<beans>


Running the program:


public class Runner 
{
public static void main( String[] args )
{
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"initMethod.xml"});

StudentService stud =
(StudentService)context.getBean("studentService");

System.out.println(stud );

context.close();
}
}

No comments:

Post a Comment

Chitika