springBoot项目打包war包部署到tomcat
第一步:修改pom.xml
变成war包
<groupId>com.example</groupId>
<artifactId>springdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
排除org.springframework.boot依赖中的tomcat内置容器,这是很重要的一步
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
添加对servlet API的依赖
<!-- jsp支持开启 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- servlet支持开启 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
继承SpringBootServletInitializer
,并覆盖它的 configure
方法,如下图代码,为什么需要提供这样一个SpringBootServletInitializer子类并覆盖它的config方法呢,我们看下该类原代码的注释:
/**Note that a WebApplicationInitializer is only needed if you are building a war file and
* deploying it. If you prefer to run an embedded container then you won’t need this at
* all.
如果我们构建的是war包并部署到外部tomcat则需要使用它,如果使用内置servlet容器则不需要,外置tomcat环境的配置需要这个类的configure方法来指定初始化资源。
@SpringBootApplication
@EnableAutoConfiguration
@MapperScan(basePackages = {"com.example.springdemo"})
public class SpringdemoApplication extends SpringBootServletInitializer {
/**
* 需要把web项目打成war包部署到外部tomcat运行时需要改变启动方式
*/
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringdemoApplication.class);
}
// springboot运行后此方法首先被调用
// 实现CommandLineRunner抽象类中的run方法
public static void main(String[] args) {
SpringApplication.run(SpringdemoApplication.class, args);
}
}
如果像我一样在webapp的WEB-INF的lib下引入了第三方的jar包就还需要把第三方jar包加进来
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webResources>
<resource>
<directory>src/main/webapp</directory>
<targetPath>WEB-INF/lib/</targetPath>
<includes>
<include>**/*.jar</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
</build>
最后如果编辑器中包含了自带的maven则使用以下命令打war包(不然就在前面加maven clean package。。)
clean package -Dmaven.test.skip=true
这样把war包打成功之后,可以在项目上的target文件夹中找到,自己可以重命名,最后放到自己tomcat服务器中的webapp下运行就可以了
还没有评论,来说两句吧...