Spring Boot:如何将另一个WAR文件添加到嵌入式tomcat?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (53)

Spring Boot的嵌入式tomcat非常方便,适用于开发和部署。

但是如果应该添加另一个(第三方)WAR文件(例如,GeoServer)呢?

也许以下是正常程序:

  1. 安装普通的Tomcat服务器。
  2. 将Spring Boot应用程序构建为WAR文件,并将其添加到Tomcat的webapps文件夹中。
  3. 还要将另一个(第三方)WAR文件添加到webapps文件夹。

但如果可以进行以下配置,那就太好了。

  1. 将Spring启动应用程序构建为独立的Jar,其中包括嵌入式Tomcat。
  2. 部署Spring启动应用程序Jar。
  3. 将另一个(第三方)WAR文件添加到嵌入式Tomcat识别的文件夹中。
  4. 使用嵌入式Tomcat提供Spring引导应用程序内容和另一个WAR的内容。

怎么做到呢?

UPDATE

当spring引导应用程序由胖jar(=可执行jar)构成时,答案中的代码是不够的。修订后的内容如下:

@Bean
public EmbeddedServletContainerFactory servletContainerFactory() {
    return new TomcatEmbeddedServletContainerFactory() {

        @Override
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
                Tomcat tomcat) {
            try {
                Context context = tomcat.addWebapp("/foo", "/path/to/foo.war");
                WebappLoader loader =
                    new WebappLoader(Thread.currentThread().getContextClassLoader());
                context.setLoader(loader);
            } catch (ServletException ex) {
                throw new IllegalStateException("Failed to add webapp", ex);
            }
            return super.getTomcatEmbeddedServletContainer(tomcat);
        }

    };
}

由于系统类加载器无法加载胖jar中的jar文件,因此必须指定显式父类加载器。否则,附加WAR无法将库jar加载到添加WAR的spring boot应用程序的fat jar中。

提问于
用户回答回答于

您可以使用添加war文件到嵌入式Tomcat Tomcat.addWebapp。正如其javadoc所说,它“相当于向Tomcat的web应用程序目录添加Web应用程序”。要在Spring Boot中使用此API,您需要使用自定义TomcatEmbeddedServletContainerFactory子类:

@Bean
public EmbeddedServletContainerFactory servletContainerFactory() {
    return new TomcatEmbeddedServletContainerFactory() {

        @Override
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
                Tomcat tomcat) {
            // Ensure that the webapps directory exists
            new File(tomcat.getServer().getCatalinaBase(), "webapps").mkdirs();

            try {
                Context context = tomcat.addWebapp("/foo", "/path/to/foo.war");
                // Allow the webapp to load classes from your fat jar
                context.setParentClassLoader(getClass().getClassLoader());
            } catch (ServletException ex) {
                throw new IllegalStateException("Failed to add webapp", ex);
            }
            return super.getTomcatEmbeddedServletContainer(tomcat);
        }

    };
}
用户回答回答于

花了一段时间来解决Spring Boot 2的问题,因为没有一个答案对我有用。我终于想到了这个(我开启了SSL):WarRun.java下面有Gradle依赖项,以使其工作。

它给出了什么:

带有上下文路径的嵌入式tomcat /在https:// localhost:8070

sample.war at https:// localhost:8070 / sample

SampleWebApp.war位于https:// localhost:8070 / yo

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Properties;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.ClassPathResource;

@ComponentScan({ "com.towianski.controllers" })
@SpringBootApplication
@Profile("server")
public class WarRun extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(WarRun.class).web(  WebApplicationType.SERVLET );
    }

    public static void main(String[] args) {

        SpringApplication app = new SpringApplication(WarRun.class);
        System.out.println( "Entered WarRun.main");

        String loggingFile = "";
        String dir = "";

        for ( int i = 0; i < args.length; i++ )
            {
//            logger.info( "** args [" + i + "] =" + args[i] + "=" );
            System.out.println( "** args [" + i + "] =" + args[i] + "=" );
            if ( args[i].toLowerCase().startsWith( "-dir" ) )
                {
                dir = args[i].substring( "-dir=".length() );
                }
            else if ( args[i].toLowerCase().startsWith( "--logging.file" ) )
                {
                loggingFile = args[i].substring( "--logging.file=".length() );
                stdOutFilePropertyChange( loggingFile );
                stdErrFilePropertyChange( loggingFile );
                }
            }

        Properties properties = new Properties();
//        properties.setProperty( "spring.resources.static-locations",
//                               "classpath:/home/stan/Downloads" );
        properties.setProperty( "server.port", "8070" );
//        System.setProperty("server.servlet.context-path", "/prop");     <--- Will set embedded Spring Boot Tomcat context path
        properties.setProperty( "spring.security.user.name", "stan" );
        properties.setProperty( "spring.security.user.password", "stan" );
        System.out.println( "Entered WarRun.main after set properties");
        app.setDefaultProperties(properties);
        System.out.println( "Entered WarRun.main after call set props. before app.run");

        app.run(args);
        System.out.println( "Entered WarRun.main after app.run()");
    }

    @Bean
    public ServletWebServerFactory servletContainer() {
        return new TomcatServletWebServerFactory() {
            protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
                System.out.println( "tomcat.getServer().getCatalinaBase() =" + tomcat.getServer().getCatalinaBase() + "=" );
                new File(tomcat.getServer().getCatalinaBase(), "/webapps").mkdirs();
    //            try {
    //                Files.copy( (new File( "/home/stan/Downloads/sample.war" ) ).toPath(), (new File( tomcat.getServer().getCatalinaBase() +"/webapp/sample.war") ).toPath());
    //            } catch (IOException ex) {
    //                Logger.getLogger(WarRun.class.getName()).log(Level.SEVERE, null, ex);
    //            }
                try {
                    System.out.println( "Entered ServletWebServerFactory servletContainer()");
                    Context context2 = tomcat.addWebapp("/sample", new ClassPathResource("file:/home/stan/Downloads/sample.war").getFile().toString());
                    Context context3 = tomcat.addWebapp("/yo", new ClassPathResource("file:/home/stan/Downloads/SampleWebApp.war").getFile().toString());
    //                Context context = tomcat.addWebapp("/what", new ClassPathResource( "file:" + tomcat.getServer().getCatalinaBase() +"/webapps/sample.war" ).getFile().toString() );

                    context2.setParentClassLoader(getClass().getClassLoader());
                    context3.setParentClassLoader(getClass().getClassLoader());

    //  also works but above seems better
    //                WebappLoader loader2 = new WebappLoader(Thread.currentThread().getContextClassLoader());
    //                WebappLoader loader3 = new WebappLoader(Thread.currentThread().getContextClassLoader());
    //                context2.setLoader(loader2);
    //                context3.setLoader(loader3);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                return super.getTomcatWebServer(tomcat);
            }
        };
    }
}

摇篮:

apply plugin: 'war'

war {
    enabled = true
}

. . . .
dependencies {
    compile("org.springframework.boot:spring-boot-starter:2.1.6.RELEASE")
    compile("org.springframework.boot:spring-boot-starter-web:2.1.6.RELEASE") 
    compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-jasper', version: '9.0.21'
    compile("org.springframework.boot:spring-boot-starter-security:2.1.6.RELEASE")
    compile 'org.apache.httpcomponents:httpclient:4.5.7'
    compile group: 'org.codehaus.groovy', name: 'groovy-all', version: '2.5.6'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.jcraft:jsch:0.1.55'

    testCompile group: 'junit', name: 'junit', version: '4.12'
}

扫码关注云+社区

领取腾讯云代金券