如何 运行 在外部 Tomcat 服务器中为 WAR 文件设置代码

How to run setup code for WAR file in External Tomcat Server

我有一个正在构建的 spring 启动应用程序,在开始时,我需要检查一些系统文件并使用应用程序在其中找到的信息准备一些数据库池。通常,我会将此包含在 @SpringBootApplication 注释 class 的主要方法中,但是,当我将我的应用程序作为 WAR 文件部署到外部 Tomcat 服务器时,主要 class 似乎没有 运行。我已经检查过你应该在主 class 中拥有什么,我的主应用程序 class 现在看起来像这样:

package com.companyname.projectname;

import com.companyname.projectname.database.DatabasePoolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class WebApplication extends SpringBootServletInitializer {

    private static final Logger logger = LoggerFactory.getLogger(WebApplication.class);

    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(WebApplication.class, args);
        DatabasePoolManager dpm = applicationContext.getBean(DatabasePoolManager.class);
        dpm.setUpPools();
        logger.error("\n\nIS ANYBODY OUT THERE?\n\n");
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        logger.error("\n\nIS ANYBODY OUT THERE? (But in the configure method)\n\n");
        return builder.sources(WebApplication.class);
    }

}

由于 extends 和覆盖 configure,这与我原来的设置不同。

到目前为止,我的 Intellij IDE 仍然 运行 没问题,但是一旦移动并部署到 tomcat 服务器,就会出现 none 日志消息.该应用程序仍然有效,但显然缺少一些授予其功能(与数据库的连接)的设置。当我将此应用程序部署为 WAR 文件时,我将如何在应用程序启动时 运行 设置一些设置代码?

再次感谢上面评论中的 M.Deinum,运行 启动后,我使用了如下所示的新 class:

package com.companyname.projectname;

import com.companyname.projectname.database.DatabasePoolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class AppStartupRunner implements ApplicationRunner {

    @Autowired
    ApplicationContext applicationContext;

    private static final Logger logger = LoggerFactory.getLogger(AppStartupRunner.class);

    @Override
    public void run(ApplicationArguments args) throws Exception {
        DatabasePoolManager dpm = applicationContext.getBean(DatabasePoolManager.class);
        dpm.setUpPools();
    }
}