下面列出了在 JavaEE 应用程序中获取生命周期回调的几种流行方法。
创建 javax.servlet.ServletContextListener 实现
如果您的 .ear 文件中有一个 Web 组件(嵌入的 .war)或者您的部署本身就是一个 .war,您可以添加ServletContextListener http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html给你的web.xml
并在服务器启动或关闭时获取回调。
Example:
package com.stackoverflow.question
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
public class MyServletContextListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent contextEvent) {
/* Do Startup stuff. */
}
@Override
public void contextDestroyed(ServletContextEvent contextEvent) {
/* Do Shutdown stuff. */
}
}
然后将此配置添加到您的web.xml
部署描述符。
$WAR_ROOT/WEB-INF/web.xml
.
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee">
<listener>
<listener-class>com.stackoverflow.question.MyServletContextListener</listener-class>
</listener>
</web-app>
创建 EJB 3.1 @Startup Bean
此方法使用 EJB 3.1 单例从服务器获取启动和关闭回调。
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Startup;
import javax.ejb.Singleton;
@Singleton
@Startup
public class LifecycleBean {
@PostConstruct
public void init() {
/* Startup stuff here. */
}
@PreDestroy
public void destroy() {
/* Shutdown stuff here */
}
}