先需要明确的是,该项目打包的形态是可执行的jar包,还是在tomcat下运行的war包。
springboot自带的maven打包
1.创建一个springboot web项目
1.api控制层HelloWorld.java
@RestController
@RequestMapping("/hello")
public class HelloWorld {
@RequestMapping("/helloworld")
public String helloworld(){
return "hello world!";
}
}
2.主程序类HelloworldMainApplication.java
@SpringBootApplication
public class HelloworldMainApplication extends SpringBootServletInitializer {
//springboot项目打包成war包,使用外置的tomcat启动
//1、首先需要继承 org.springframework.boot.context.web.SpringBootServletInitializer类
//2、然后重写configure(SpringApplicationBuilder builder)方法
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
// 注意这里要指向原先用main方法执行的Application启动类
return builder.sources(HelloworldMainApplication.class);
}
public static void main(String[] args){
SpringApplication.run(HelloworldMainApplication.class);
}
}
3.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springbood</groupId>
<artifactId>SpringBoodTest1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- <dependency>
移除嵌入式tomcat插件
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>-->
</dependencies>
<build>
<finalName>app1</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.4.11</version>
</plugin>
</plugins>
</build>
</project>
如果是jar包
需在pom.xml指定打成的包为:
<packaging>jar</packaging>
如果是war包。
需在pom.xml指定打成的包为:
<packaging>war</packaging>
并通过标签在打包的时候排除tomcat依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
添加插件
<build>
<finalName>app1</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.4.11</version>
</plugin>
</plugins>
</build>
<finalName>标签是指定打包之后的名称
在pom.xml中添加完相应的标签之后,我们只需在项目同级(pom.xml同级)输入
mvn clean package
即可完成打包
如果想排除测试代码,则可以输入:
mvn clean package -Dmaven.test.skip=true
来进行打包。
或者使用idea maven进行打包