程序打包部署一般有两种,jar和war,本文以打war包为例,部署springboot项目。
首先,创建一个springboot项目(此处就不在多说如何创建了),修改pom.xml文件
1 <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"> 2 <modelVersion>4.0.0</modelVersion> 3 <groupId>com.allen.springboot.learn</groupId> 4 <artifactId>springboot_helloworld</artifactId> 5 <version>0.0.1-SNAPSHOT</version> 6 7 <packaging>war</packaging> 8 9 <parent> 10 <groupId>org.springframework.boot</groupId> 11 <artifactId>spring-boot-starter-parent</artifactId> 12 <version>1.5.10.RELEASE</version> 13 </parent> 14 15 <dependencies> 16 <!-- web 依赖 --> 17 <dependency> 18 <groupId>org.springframework.boot</groupId> 19 <artifactId>spring-boot-starter-web</artifactId> 20 <!-- 移除嵌入式tomcat插件 --> 21 <exclusions> 22 <exclusion> 23 <groupId>org.springframework.boot</groupId> 24 <artifactId>spring-boot-starter-tomcat</artifactId> 25 </exclusion> 26 </exclusions> 27 </dependency> 28 <dependency> 29 <groupId>org.springframework.boot</groupId> 30 <artifactId>spring-boot-starter-tomcat</artifactId> 31 <!--scope属性设置为provided,这样在最终形成的WAR中不会包含这个JAR包,因为Tomcat或Jetty等服务器在运行时将 会提供相关的API类 --> 32 <scope>provided</scope> 33 </dependency> 34 </dependencies> 35 36 <build> 37 <!-- 生成的包默认会带有版本号,此处指定生成的war文件的名称 --> 38 <finalName>springboot_helloworld</finalName> 39 </build> 40 41 </project>
其次,创建一个Servlet的初始化类,并继承SpringBootServletInitializer,以在web容器启动时执行springboot程序的启动类main方法
1 package com.learn.springboot.App; 2 3 import org.springframework.boot.builder.SpringApplicationBuilder; 4 import org.springframework.boot.web.support.SpringBootServletInitializer; 5 6 public class ServletInitializer extends SpringBootServletInitializer { 7 8 @Override 9 protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { 10 // 注意这里要指向原先用main方法执行的Application启动类 11 return builder.sources(Application.class); 12 } 13 14 }
最后就是打包了,我们使用eclipse集成maven插件来打包,点击选中pom.xml,右击run as ---> run configuration --->goals:package --->run。这时会在工程文件的target目录下生成对应的war包文件,把war放在tomcat的webapps目录下,启动tomcat即可。