【问题标题】:What is the main method of a WAR file?WAR文件的主要方法是什么?
【发布时间】:2015-04-20 12:48:10
【问题描述】:

最近,我重新打包了我的 java spring 应用程序,使其成为一个 WAR 文件,以便在 tomcat 中部署。经过一些测试,我注意到 public static void main(String[] args) 没有被执行。我的应用程序的一些必要初始化在main 中完成。 WAR 文件中是否有类似main 的方法? WAR 文件中运行某些初始化的适当位置是什么?

【问题讨论】:

  • 可以在web.xml文件中指定启动时执行一个类...
  • 这看起来特定于 Spring Boot - 请更新标签,目前发布的两个答案都没有考虑到这一事实。
  • 花了 2 天时间尝试不同的解决方案后,我意识到主要问题是主要功能未在 war 文件中执行。

标签: java spring tomcat


【解决方案1】:

您可以将侦听器添加到您的 web.xml 文件中:

<listener>
    <description>Application startup and shutdown events</description>
    <display-name>Test</display-name>
    <listener-class>com.package.package.StartClass</listener-class>
</listener>

public class StartClass implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
         //Context destroyed code here
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent)
    {
        //Context initialized code here
    }
}

【讨论】:

  • 您可能想要更改display-name :-)
  • @AaronDigulla 你的意思是他可能想更改显示名称大声笑这只是一个例子......
  • 我没有 web.xml 文件,但是用 SpringBootServletInitializer 来做。
  • @user1785730:用@WebListener 注释你的类。见docs.oracle.com/javaee/6/api/javax/servlet/annotation/…
  • 我在一个项目中工作,web.xml 有三个监听器,它们都不属于项目文件——它们是关于一些 Spring 类的。所以,指向起始类的不是监听器。
【解决方案2】:

好吧,您必须在 web.xml 中创建一个侦听器,该侦听器将在启动时由容器调用。

<listener>
    <listener-class>com.rdv.example.WebAppContext</listener-class>
</listener>

这个类将实现ServletContextListener

public class WebAppContext implements ServletContextListener {

public void contextInitialized(ServletContextEvent servletContextEvent) {
// Do your processing that you are trying to do in main method.
}

【讨论】:

    【解决方案3】:

    我找到了另一种方式,它独立于 spring 和 tomcat:@PostConstruct 注释。在代码中:

    @PostConstruct
    public void init() {
        // initialization code goes here
    }
    

    无论我是独立运行应用程序还是在 tomcat 中运行,都会执行此方法。

    更多信息请见How to call a method after bean initialization is complete?Init method in Spring Controller (annotation version)

    【讨论】:

      猜你喜欢
      • 2018-06-06
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 2012-04-06
      • 1970-01-01
      • 2020-06-25
      • 1970-01-01
      • 2011-07-14
      相关资源
      最近更新 更多