修改pom.xml添加一下代码
<!-- 1.packaging修改成war -->
<packaging>war</packaging>
<!-- 2.添加spring-boot-starter-tomcat的provided依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>provided</version>
</dependency>
<!-- 3.添加maven-war-plugin插件 -->
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
<!-- jar包插件,将上面代码去掉即可 -->
<!--<build>
<finalName>${project.artifactId}-${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>-->
</build>
启动类继承SpringBootServletInitializer类
# 如果要打jar包,需要将继承类给去掉
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder){
return builder.sources(MainApplication.class);
}
}
现在就可以运行jar和war包了
进入项目根目录,执行打包命令,打成war包
mvn clean package
将生产的war包复制到tomcat的webapps目录下,重启tomcat
访问地址
注意:如果war放在webapps下,访问的时候需要加项目路径,如果放在ROOT目录下就不用加项目路径