使用外部容器运行spring-boot项目
spring boot项目可以快速构建web应用,其内置的tomcat容器也十分方便我们的测试运行。
spring-boot项目需要部署在外部容器中的时候,spring-boot导出的war包无法再容器(tomcat)中运行或运行时报错。
1.修改打包形式
在pom.xml里设置 <packaging>war</packaging>
2.移除嵌入式tomcat插件
spring-boot-starter-tomcat是spring boot默认就会配置的,即上面说有内嵌tomcat,可通过下面两种方式移除
<!--spring boot tomcat(默认可以不用配置,但当需要把当前web应用布置到外部servlet容器时就需要配置,并将scope配置为provided)-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 移除嵌入式tomcat插件 -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
3.添加servlet-api依赖
scope为provided只在编译时使用,打包时不会包含。
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
或者
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>8.0.36</version>
<scope>provided</scope>
</dependency>
4.修改启动类,并重定初始化方法
基于servlet3.0,已经可以不需要web.xml了。spring为我们提供了WebApplicationInitializer接口,由servlet3.0自动引导。
提供一个SpringBootServletInitializer子类,并覆盖它的configure方法。
@SpringBootApplication
@ComponentScan
public class GislandpriceApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(GislandpriceApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
builder.sources(this.getClass());
return super.configure(builder);
}
}
5.使用maven的package进行打包。
6.spring boot默认是/,这样直接通过http://ip:port/就可以访问到index页面,如果要修改为http://ip:port/path/访问的话,那么需要在Application.properties文件中加入server.servlet.context-path=/yourpath,比如:spring-boot,那么访问地址就是http://ip:port/spring-boot路径 。
直接用jar运行项目
以往的WEB程序需要打成WAR包,部署到Tomcat上,而Spring Boot支持打包成JAR的形式,就算是JAR里面包含图片、页面等,也是支持的。另外使用JAR包的方式也方便部署到Docker上。
1.修改为jar包形式
<groupId>com.springboot</groupId>
<artifactId>study</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
2.maven打jar包
3.运行
java -jar study-0.0.1-SNAPSHOT.jar
最后欢迎大家访问我的个人网站:1024s