Sunday, March 20, 2011

@PostConstruct and @PreDestroy example

In this tutorial you will learn how to implement the @PostConstruct and @PreDestroy which work similar to init-method and destroy-method in bean configuration file or implement the InitializingBean and DisposableBean in your bean class. To use @PostConstruct and @PreDestroy you have to register the CommonAnnotationBeanPostProcessor at bean configuration or specifying the <context:annotation-config /> in the bean configuration file.

Consider the service bean:

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class StudentService {

String message;

public String getMessage() {
return message;
}

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

@PostConstruct
public void initIt() throws Exception {
System.out.println("After properties has been set : " + message);
}

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

}


Bean config file:


<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"
>

<context:annotation-config />

<bean id="studentService" class="com.xxxx.StudentService">
<property name="message" value="property message" />
</bean>

</beans>


No comments:

Post a Comment

Chitika