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=""
<!-- our bean here -->
<bean id="studentService" class="com.xxxx.StudentService"
init-method="initIt" destroy-method="cleanUp">
<property name="message" value="property message" />


Running the program:

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

StudentService stud =

System.out.println(stud );


No comments:

Post a Comment