Spring 引导:Web.xml 和嵌入式服务器 jar

Spring Boot: Web.xml and embedded server jar

我正在尝试将遗留的 spring-mvc 应用程序转换为 Spring 启动(以便拥有一个独立的 JAR,以便更轻松地升级到 Java-8)。

我认为没有理由用代码替换我现有的 web.xml 文件,因为代码看起来像配置,而且 web.xml 更成熟。

是否可以在 Spring 启动应用程序(嵌入式 JAR 模式)中使用我现有的 web.xml?

编辑:我也想避免使用@EnableAutoConfiguration

谢谢

您不需要 Spring-Boot 来拥有独立的 JAR,您真正需要的只是嵌入式 Tomcat,或 Jetty。

public static void main(String[] a)创建一个class,这个Class将在java -jar myWebapp.jar命令"executed"时使用这个Class。

main方法中,您可以启动Embedded Tomcat或Jetty,并通过引用现有的web.xml.

使其加载您的webapp

好的,多亏了 Mecon,我稍微接近了一点。我不得不删除 web.xml 中的 ContextLoaderListener;还必须导入 xml Spring 配置,即使它在 contextConfigLocation 中被引用。

@Configuration
@ComponentScan
@EnableAutoConfiguration
@ImportResource(value = {"classpath:/webapp-base.xml"})
public class WebApp {

    @Autowired
    private ServerProperties serverProperties;

    @Autowired
    private MediaConfiguration mediaConfig;

        @Bean
        public EmbeddedServletContainerFactory servletContainer() {
            JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory();
            factory.setContextPath(serverProperties.getContextPath());
            factory.addConfigurations(new WebXmlConfiguration());
            factory.addServerCustomizers(server -> {
                    List<Handler> resourceHandlers = getResourceHandlers();
                    Handler original = server.getHandler();

                    HandlerList handlerList = new HandlerList();
                    Handler[] array = getHandlers(original, resourceHandlers);
                    handlerList.setHandlers(array);

                    server.setHandler(handlerList);
                }
            );
            return factory;
        }

    private List<Handler> getResourceHandlers() {
        return mediaConfig.getMappings().stream().map(m -> {
            ContextHandler contextHandler = new ContextHandler(m.getUrlpath());
            ResourceHandler resourceHandler = new ResourceHandler();
            resourceHandler.setResourceBase(m.getFilepath());
            contextHandler.setHandler(resourceHandler);
            return contextHandler;
        }).collect(Collectors.toList());
    }

    private Handler[] getHandlers(Handler original, List<Handler> resourceHandlers) {
        ArrayList<Handler> handlers = new ArrayList<>();
        handlers.add(original);
        handlers.addAll(resourceHandlers);
        return handlers.toArray(new Handler[resourceHandlers.size()+1]);
    }

    public static void main(String[] args) {
        SpringApplication.run(WebApp.class, args);
    }

}