springBoot项目打包war包部署到tomcat

谁践踏了优雅 2022-05-12 06:44 512阅读 0赞

第一步:修改pom.xml

变成war包

  1. <groupId>com.example</groupId>
  2. <artifactId>springdemo</artifactId>
  3. <version>0.0.1-SNAPSHOT</version>
  4. <packaging>war</packaging>

排除org.springframework.boot依赖中的tomcat内置容器,这是很重要的一步

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. <exclusions>
  5. <exclusion>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-tomcat</artifactId>
  8. </exclusion>
  9. </exclusions>
  10. </dependency>

添加对servlet API的依赖

  1. <!-- jsp支持开启 -->
  2. <dependency>
  3. <groupId>org.apache.tomcat.embed</groupId>
  4. <artifactId>tomcat-embed-jasper</artifactId>
  5. </dependency>
  6. <!-- servlet支持开启 -->
  7. <dependency>
  8. <groupId>javax.servlet</groupId>
  9. <artifactId>javax.servlet-api</artifactId>
  10. </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方法来指定初始化资源。

  1. @SpringBootApplication
  2. @EnableAutoConfiguration
  3. @MapperScan(basePackages = {"com.example.springdemo"})
  4. public class SpringdemoApplication extends SpringBootServletInitializer {
  5. /**
  6. * 需要把web项目打成war包部署到外部tomcat运行时需要改变启动方式
  7. */
  8. @Override
  9. protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
  10. return application.sources(SpringdemoApplication.class);
  11. }
  12. // springboot运行后此方法首先被调用
  13. // 实现CommandLineRunner抽象类中的run方法
  14. public static void main(String[] args) {
  15. SpringApplication.run(SpringdemoApplication.class, args);
  16. }
  17. }

如果像我一样在webapp的WEB-INF的lib下引入了第三方的jar包就还需要把第三方jar包加进来

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-maven-plugin</artifactId>
  6. </plugin>
  7. <plugin>
  8. <groupId>org.apache.maven.plugins</groupId>
  9. <artifactId>maven-war-plugin</artifactId>
  10. <configuration>
  11. <webResources>
  12. <resource>
  13. <directory>src/main/webapp</directory>
  14. <targetPath>WEB-INF/lib/</targetPath>
  15. <includes>
  16. <include>**/*.jar</include>
  17. </includes>
  18. </resource>
  19. </webResources>
  20. </configuration>
  21. </plugin>
  22. </plugins>
  23. </build>

最后如果编辑器中包含了自带的maven则使用以下命令打war包(不然就在前面加maven clean package。。)

  1. clean package -Dmaven.test.skip=true

这样把war包打成功之后,可以在项目上的target文件夹中找到,自己可以重命名,最后放到自己tomcat服务器中的webapp下运行就可以了

发表评论

表情:
评论列表 (有 0 条评论,512人围观)

还没有评论,来说两句吧...

相关阅读