Oli*_*ver 17 java timer java-ee
我有一个Java EE应用程序,它应该在部署后与外部系统一起启动同步过程.
我怎么能实现这个要求?
Dev*_*Dev 22
下面列出了几种在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. */
}
}
Run Code Online (Sandbox Code Playgroud)
然后将此配置添加到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>
Run Code Online (Sandbox Code Playgroud)
创建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 */
}
}
Run Code Online (Sandbox Code Playgroud)
我测试了使用@Startup和@PostConstruct注释的建议解决方案.事实证明,在注释@PostConstruct完所有方法之前,Glassfish不会完成应用程序的部署.所以在我的情况下,部署需要几分钟到一个小时.
但我想出了一种不同的方式来实现我想要的东西.最好的解决方案似乎是一个定时器回调方法,它在执行后取消它的定时器.
@Stateless
public class SynchronisationService {
@Schedule(hour = "*", minute = "*", persistent = false)
protected void init(Timer timer)
{
doTheSync();
timer.cancel();
}
}
Run Code Online (Sandbox Code Playgroud)
如果重新启动应用程序服务器,则使用非持久性计时器可以重新创建计时器.