问题描述
我需要在 Tomcat 启动时删除临时文件,传递到包含临时文件的文件夹在 applicationContext.xml 中.
I need to remove temp files on Tomcat startup, the pass to a folder which contains temp files is in applicationContext.xml.
有没有办法只在 Tomcat 启动时运行一个方法/类?
Is there a way to run a method/class only on Tomcat startup?
推荐答案
您可以编写一个 ServletContextListener
从 contextInitialized()
方法调用您的方法.您在 web.xml 中将侦听器附加到您的 web 应用程序,例如
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.
<listener>
<listener-class>my.Listener</listener-class>
</listener>
和
package my;
public class Listener implements javax.servlet.ServletContextListener {
public void contextInitialized(ServletContext context) {
MyOtherClass.callMe();
}
}
严格来说,这只会在 webapp 启动时运行一次,而不是在 Tomcat 启动时运行,但这可能是一样的.
Strictly speaking, this is only run once on webapp startup, rather than Tomcat startup, but that may amount to the same thing.
这篇关于有没有办法只在 Tomcat/Wildfly/Glassfish 启动时运行方法/类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!