我有一个Java EE应用程序,应在部署后启动与外部系统的同步过程。
我该如何实现这个需求?
我有一个Java EE应用程序,应在部署后启动与外部系统的同步过程。
我该如何实现这个需求?
以下列出了在JavaEE应用程序中获取生命周期回调的几种流行方法。
创建一个javax.servlet.ServletContextListener实现
如果您有一个.web组件到您的.ear文件(嵌入式.war)或您的部署是单独的.war文件,您可以将一个 ServletContextListener
添加到您的web.xml
并在服务器启动或关闭时获得回调。
例子:
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 */
}
}
@WebListener
?你是在为 OP 搜索答案吗? - BalusC@WebListener
,我一直使用 web.xml
配置 ServletContextListeners
。我不太确定它是如何工作的,所以我不想给出错误的建议。另外,我哪个包搞错了? - Dev<listener>
需要闭合标签 </listener>
。 - Marc Bouvier@Startup
和 @PostConstruct
注解的建议解决方案。结果发现,Glassfish在所有使用@PostConstruct
注解的方法完成之前不会完成应用程序的部署。因此,在我的情况下,部署需要几分钟甚至一个小时。@Stateless
public class SynchronisationService {
@Schedule(hour = "*", minute = "*", persistent = false)
protected void init(Timer timer)
{
doTheSync();
timer.cancel();
}
}
@Startup
和@PostConstruct
注释在应用程序启动时执行任务。@PostConstruct
注解应该仅用于需要几分钟完成的初始化任务。与外部系统的同步需要更长时间。因此,同步不应绑定到bean本身的初始化上。 - Oliver