How to easily convert a SpringBoot into a war package (transfer)

Why make SpringBoot a war package

Under normal circumstances, the SpringBoot project is in the form of a jar package, through the command line:

java -jar demo.jar

to run, and SpringBoot is an embedded Tomcat server, so every restart is a new Tomcat server. Because of this, there is also a problem: 
if the files uploaded to the project are saved in the project, the files will be lost after restarting. For example, if we upload an avatar, after restarting the project, the avatar is gone. And if the file is saved in the local disk, there is no way to get the tags in the html. Therefore, we need to package the SpringBoot project into a war package and put it into Tomcat to run.

Modification method

Add the following dependencies to the pom.xml file:

 <!--因配置外部TOMCAT 而配置-->
<dependency>
            <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

At the same time, change the jar at the head of the pom.xml file to war

    <groupId>com.star</groupId>
    <artifactId>yiyong</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <!--<packaging>jar</packaging>--> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Finally, change the startup class from

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

change into

@SpringBootApplication
public class YiyongApplication extends SpringBootServletInitializer{ @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(YiyongApplication.class); } public static void main(String[] args) { SpringApplication.run(YiyongApplication.class, args); } }

Note: This class inherits SpringBootServletInitializer and overrides the configure method, which is the key.

Package deployment

Double-click the package in the Maven column on the right side of IDEA and wait for Build Success. 
write picture description here 
Then put the war package in the target directory into the webapps directory of tomcat, start tomcat, and it can be automatically decompressed and deployed. 
Finally type in the browser

http://localhost:[端口号]/[打包项目名]/

 

Published successfully

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325522751&siteId=291194637