Spring Boot: How to add another WAR files to the embedded tomcat?

后端 未结 3 1779
逝去的感伤
逝去的感伤 2020-11-28 08:28

Spring Boot\'s embedded tomcat is very handy, for both development and deploy.

But what if an another (3rd-party) WAR file (for example, GeoServer) should be added?<

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 08:37

    You can add a war file to embedded Tomcat using Tomcat.addWebapp. As its javadoc says, it's the "equivalent to adding a web application to Tomcat's web apps directory". To use this API in Spring Boot, you need to use a custom TomcatEmbeddedServletContainerFactory subclass:

    @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);
            }
    
        };
    }
    

提交回复
热议问题