上一篇文章讲了如何创建一个SpringBoot Web项目,如何将这个项目打包呢。
打包成jar格式
因为SpringBoot项目中内嵌了了Tomcat组件,所以只需要执行打包命令即可。
mvn clean package 或者 java -jar target/spring-boot-demo-1.0-SNAPSHOT.jar
或者同时执行:
mvn clean package && java -jar target/spring-boot-demo-1.0-SNAPSHOT.jar
打包成war包,放到Tomcat中执行
- 修改启动类,使之继承 SpringBootServletInitializer 并重写 configure 方法
package com.liusj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import java.util.Arrays;
@SpringBootApplication
public class SpringbootApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SpringbootApplication.class);
}
public static void main(String[] args) throws Exception {
ApplicationContext ctx = SpringApplication.run(SpringbootApplication.class, args);
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}
2.修改pom文件,将打包方式改为war,并将内嵌的Tomcat组件可用范围改为provided
<packaging>war</packaging>
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
- 运行 mvn clean package命令打包
打包完之后在target目录中可以看到打包好的war文件
将文件复制到Tomcat安装目录下的webapps目录下,启动tomcat
在浏览器中输入:http://localhost:8080/spring-boot-demo-1.0-SNAPSHOT/