我有一个简单的 Java 应用程序,我需要一直运行它(还要在服务器重启时自动启动)。
我想过一个服务包装器,但 Windows 版本是付费的。
有没有一种方法可以将 Tomcat 配置为自动运行项目中的特定类或可以提供相同结果的任何其他解决方案?
最佳答案
我认为您需要有一个同时以 tomcat 启动的应用程序(无论是 Web 还是非 Web)。
那么,您需要有一个简单的 Web 应用程序来注册一个监听器(监听应用程序启动事件,即 tomcat 启动事件)并启动您的类。
在你的 web.xml 中声明一个监听器非常简单:
<listener>
<description>application startup and shutdown events</description>
<display-name>ApplicationListener</display-name>
<listener-class>com.myapp.server.config.ApplicationListener</listener-class>
</listener>
在您的 ApplicationListener 类中,您实现了 ServletContextListener 接口(interface)。这是一个例子:
import java.io.File;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Class to listen for application startup and shutdown
*
* @author HBR
*
*/
public class ApplicationListener implements ServletContextListener {
private static Logger logger = Logger.getLogger(ApplicationListener.class);
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
logger.info("class : context destroyed");
}
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext context = servletContextEvent.getServletContext();
///// HERE You launch your class
logger.info("myapp : context Initialized");
}
}
关于java - 在 tomcat 上运行非 web java 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14999028/