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.
StudentService.java
package com.roseindia.student.services;
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");
}
}
AppMain.java
package com.roseindia.common;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.roseindia.student.services.StudentService;
public class AppMain {
public static void main(String[] args) {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "context.xml" });
StudentService stud = (StudentService) context
.getBean("studentService");
System.out.println(stud);
context.close();
}
}
context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
|
| After properties has been set : property message com.roseindia.student.services.StudentService@ec4a87 .... Cleaned everything!! |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.