SpringBoot部署 –war方式
步驟1部署方式
Springboot 和我們之前學習的web 應用程序不一樣,其本質上是一個 Java 應用程序,那么又如何部署呢?
通常來說,Springboot 部署會采用兩種方式:全部打包成一個jar,或者打包成一個war。
本知識點講解 war 的方式。
步驟2可運行項目
開發過程在前面的知識點講解過了,這里就不表了,首先在右上角下載可運行項目。
下載后解壓,比如解壓到如圖所示目錄
步驟3application
Application 修改為如下代碼
新加@ServletComponentScan注解,並且繼承SpringBootServletInitializer 。
為什么要這么改? 這是規定。。。。 要搞成war ,反正就得這么改~
package com.coding4funjava.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.support.SpringBootServletInitializer;
@SpringBootApplication
@ServletComponentScan
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
步驟4pom.xml
pom.xml修改為如下代碼,主要兩個改動
新加打包成war的聲明:
<packaging>war</packaging>
spring-boot-starter-tomcat修改為 provided方式,以避免和獨立 tomcat 容器的沖突.
表示provided 只在編譯和測試的時候使用,打包的時候就沒它了。
<?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.coding4funjava</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot</name>
<description>springboot</description>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
步驟5創建war
cd C:\Users\X7TI\Downloads\springboot
mvn clean package
這樣就在 target 目錄下 生成了一個 springboot-0.0.1-SNAPSHOT.war 文件
步驟6 重命名war包 然后部署
如果用 springboot-0.0.1-SNAPSHOT.war 這個文件名部署,那么訪問的時候就要在路徑上加上springboot-0.0.1-SNAPSHOT。 所以把這個文件重命名為 ROOT.war
然后把它放進tomcat 的webapps目錄下。
注:沒有tomcat的同學可以在右上角下載。
注: ROOT.war 並不是指訪問的時候要使用 /ROOT/hello ,而是直接使用/hello 進行訪問,ROOT表示根路徑。
步驟7啟動並測試
運行tomcat下的 bin目錄里的startup.bat, 然后就可以啟動了. 啟動后訪問如下地址測試:
http://127.0.0.1:8080/hello