1. 程式人生 > >SpringBoot:SpringBoot專案部署之Jar與War

SpringBoot:SpringBoot專案部署之Jar與War

SpringBoot:SpringBoot專案部署之Jar與War

一、Jar包部署(預設)

1.Jar包部署pom檔案中packaging為Jar。
<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/maven-v4_0_0.xsd">
    ......
    <packaging>jar</packaging>
    ......
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
<project>

2.因為SpringBoot專案內嵌tomcat,所以編譯完成後,target目錄中的jar包是可以直接用java -jar *.jar來執行的。服務的埠和請求根路徑可以設定:

server.context-path=/project
server.port=8088

二、War包部署

1.修改pom檔案
<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/maven-v4_0_0.xsd">
    ......
    <packaging>war</packaging>
    ......
    <dependencies>
    	......
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter</artifactId>
		<scope>provided</scope>
	</dependency>
	......
    <dependencies>
    <build>
  	<plugins>
    		 <plugin>
        		<groupId>org.springframework.boot</groupId>
        		<artifactId>spring-boot-maven-plugin</artifactId>
        		<executions>
        		   <execution>
        		      <goals>
        		         <goal>repackage</goal>
        		      </goals>
        		   </execution>
        		</executions>
     		</plugin>
  	 </plugins>
    </build>
<project>

spring-boot-starter-tomcat 是原來被傳遞過來的依賴,預設會打到包裡,所以我們再次引入此依賴,並指定依賴範圍為provided,這樣tomcat 相關的jar就不會打包到war 裡了。
2.新增ServletInitializer
A.方式一:Application.java直接繼承SpringBootServletInitializer

@SpringBootApplication
public class Application extends SpringBootServletInitializer{
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }
}

B.方式二:在Application同包下新建類

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
     @Override
      protected SpringApplicationBuilder configure(SpringApplicationBuilderapplication) {
              return application.sources(Application.class);
      }
}

3.使用package指令生成War包,放置到Tomcat的webapp目錄中,啟動tomcat嘗試訪問。