一、概述
Sprint Boot默认将应用打包成可独立执行的jar包。虽然这样很方便微服务式的应用部署,但是如果你仍然想打包成旧式的war包,并部署到servlet容器,例如tomcat或者jetty中,Spring Boot也提供相应的支持。
本文简要介绍如何打包成war包。
二、具体操作
1. 继承SpringBootServletInitializer,并覆写configure方法
这样就可以使用Spring Framework提供的Servlet 3.0支持,并且可以在servlet容器加载应用时进行一些配置。
一般通过主类继承SpringBootServletInitializer来实现,例如:
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
2. 更在pom.xml中的packaging为war
例如:
<packaging>war</packaging>
3. 将内置的嵌入式容器的范围改为provided
此步是为了避免Spring boot内置的servlet容器依赖和外部的servlet容器互相干扰。
一般修改如下:
<dependencies>
<!-- … -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- … -->
</dependencies>
三、为Servlet3.0之前的容器提供war包
Servlet3.0之前的容器不支持ServletContextInitializer启动,因此需要手动添加web.xml文件,并且在web.xml中配置ApplicationContext和DispatcherServlet等。
参考链接
spring boot reference 1.3.6