
You can define the moment when a method is called by using the corresponding annotations.
There are two annotations for configuring method invocation:
@PostConstruct
This annotation specifies that the method will be called before all lifecycle methods are called.
@PreDestroy
This annotation specifies that the method will be called before the servlet object is destroyed.
Using the @PostConstruct Annotation
Use this annotation at method level without any attributes.
public class PostConstructAnnot_servlet extends HttpServlet {
//…
@PostConstruct
public void postConstruct() {
//Invocation of init methods, preparative operations
System.out.println("PostConstructAnnot_servlet: "
+ " postConstruct method invoked! ");
}
//…
}
Using the @PreDestroy Annotation
Use this annotation at method level without any attributes.
public class PreDestroyAnnot_servlet extends HttpServlet {
//…
@PreDestroy
public void preDestroy(){
//Clean up any open resources
System.out.println("PreDestroyAnnot_servlet: " +
" preDestoy method invoked! ");
}
//…