Java 有没有办法只在 Tomcat/Wildfly/Glassfish 启动时运行方法/类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/158336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to run a method/class only on Tomcat/Wildfly/Glassfish startup?
提问by dcave555
I need to remove temp files on Tomcat startup, the pass to a folder which contains temp files is in applicationContext.xml.
我需要在 Tomcat 启动时删除临时文件,传递到包含临时文件的文件夹在 applicationContext.xml 中。
Is there a way to run a method/class only on Tomcat startup?
有没有办法只在 Tomcat 启动时运行方法/类?
采纳答案by skaffman
You could write a ServletContextListener
which calls your method from the contextInitialized()
method. You attach the listener to your webapp in web.xml, e.g.
您可以编写一个ServletContextListener
从contextInitialized()
方法调用您的方法的方法。您在 web.xml 中将侦听器附加到您的 webapp,例如
<listener>
<listener-class>my.Listener</listener-class>
</listener>
and
和
package my;
public class Listener implements javax.servlet.ServletContextListener {
public void contextInitialized(ServletContext context) {
MyOtherClass.callMe();
}
}
Strictly speaking, this is only run once on webapp startup, rather than Tomcat startup, but that may amount to the same thing.
严格来说,这只会在 webapp 启动时运行一次,而不是在 Tomcat 启动时运行,但这可能等同于同一件事。
回答by Jonny Buchanan
I'm sure there must be a better way to do it as part of the container's lifecycle (edit: Hank has the answer - I was wondering why he was suggesting a SessonListener
before I answered), but you could create a Servlet which has no other purpose than to perform one-time actions when the server is started:
我敢肯定,作为容器生命周期的一部分,必须有更好的方法来做到这一点(编辑:Hank 有答案 - 我想知道他为什么SessonListener
在我回答之前提出建议),但是您可以创建一个没有其他的 Servlet目的不是在服务器启动时执行一次性操作:
<servlet>
<description>Does stuff on container startup</description>
<display-name>StartupServlet</display-name>
<servlet-name>StartupServlet</servlet-name>
<servlet-class>com.foo.bar.servlets.StartupServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
回答by Alexander Drobyshevsky
You can also use (starting Servlet v3) an annotated aproach (no need to add anything to web.xml):
您还可以使用(从 Servlet v3 开始)一个带注释的方法(无需向 web.xml 添加任何内容):
@WebListener
public class InitializeListner implements ServletContextListener {
@Override
public final void contextInitialized(final ServletContextEvent sce) {
}
@Override
public final void contextDestroyed(final ServletContextEvent sce) {
}
}