定义:
首先很多人都认为这个注解是Spring提供,错的,这个是由javax.annotation-api提供注解,从Java EE5规范开始,增加了两个影响Servlet生命周期的注解,这两个注解都是被用来修饰一个非静态的void()方法。
@PostContruct:,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化或者servlet容器初始化的时候执行该方法。
被@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。
用法
@PostConstruct
@PostConstruct
public void someMethod(){}
@PreDestroy
public void someMethod(){}
@PostConstruct注解的方法在项目启动的时候执行这个方法,也可以理解为在spring容器启动的时候执行,可作为一些数据的常规化加载,比如数据字典之类,加载缓存之类的。
如果想在生成对象时候完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么就无法在构造函数中实现。为此,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。
调用顺序:
Constructor >> @Autowired >> @PostConstruct
public Class postConstructDemo {
@Autowired
private serviceComponent b;
public postConstructDemo() {
System.out.println("此时b还未被注入: b = " + b);
}
@PostConstruct
private void init() {
System.out.println("@PostConstruct将在依赖注入完成后被自动调用: b = " + b);
}
}
@PreDestroy
这个就相对简单,在容器卸载之前可以实现调用它;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AnnotationServlet extends HttpServlet {
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss.SSS");//设置日期格式,精确到毫秒
public AnnotationServlet(){
System.out.println("时间:"+df.format(new Date())+"执行构造函数...");
}
public void destroy() {
this.log("时间:"+df.format(new Date())+"执行destroy()方法...");
//super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
@PostConstruct
public void someMethod(){
//this.log("执行@PostConstruct修饰的someMethod()方法...");//注意:这样会出错
System.out.println("时间:"+df.format(new Date())+"执行@PostConstruct修饰的someMethod()方法...");
}
@PreDestroy
public void otherMethod(){
System.out.println("时间:"+df.format(new Date())+"执行@PreDestroy修饰的otherMethod()方法...");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.log("时间:"+df.format(new Date())+"执行doGet()方法...");
}
public void init() throws ServletException {
// Put your code here
this.log("时间:"+df.format(new Date())+"执行init()方法...");
}
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
this.log("时间:"+df.format(new Date())+"执行service()方法...");
super.service(request, response);
}
}
构造函数 ⇒ PostConstruct ⇒ init ⇒ destory ⇒ predestory == 卸载;
本文深入探讨了JavaEE5规范引入的@PostConstruct和@PreDestroy注解,详细解释了它们在Servlet生命周期中的作用及调用时机。通过示例展示了如何在项目启动和卸载时执行特定方法,为依赖注入后的初始化和资源清理提供了有效手段。
968

被折叠的 条评论
为什么被折叠?



