天天看點

Spring Boot Maven插件

使用maven指令建立SpringBoot項目,請參考《使用maven指令行方式建立springBoot工程》

SpringBoot Maven插件在Maven中提供了對SpringBoot的支援,允許打包可執行jar或war并直接運作應用程式。

在~/.m2/repository/org/springframework/boot/spring-boot-dependencies/2.2.5.RELEASE/spring-boot-dependencies-2.2.5.RELEASE.pom檔案列出了spring boot 提供了的jar包依賴。SpringBoot Maven插件的配置也在其中,如果沒有,就要将下面的的配置添加到你的pom.xml檔案中:

<build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-maven-plugin</artifactId>
          <version>2.2.5.RELEASE</version>
        </plugin>
        ...
      </plugins>
    </pluginManagement>
  </build>
           

現在我們來看看Springboot maven插件提供的一些有用的指令:

指令 作用
spring-boot:run 運作Spring Boot應用程式
spring-boot:repackage 重新打包已有的jar/war,便可以使用java -jar從指令行執行它們
spring-boot:start 和 spring-boot:stop 啟動和停止Spring Boot應用程式,與run目标相反,它不會阻止并允許其他目标在應用程式上運作。 此目标通常用于內建測試場景,其中應用程式在測試套件之前啟動并在之後停止。
spring-boot:build-info 根據目前MavenProject的内容生成build-info.properties檔案,可供執行器使用。

1.spring-boot:run

~/Desktop/MyProject/springboot$ mvn spring-boot:run
           

2.spring-boot:repackage

在spring boot裡,可以直接把應用打包成為一個jar/war,然後java -jar <name>.jar指令運作啟動jar/war,不需要另外配置一個Web Server。

(1)首先,要打jar包,還是war包,需要先在pom.xml裡指定:

<project ...>
...
  <packaging>jar</packaging>
...
</project>  
           

(2)為了能夠順利重新打包你的應用程式,使用java -jar運作,需要添加下面的配置到pom.xml:

<build>
	  <plugins>
	  	<plugin>
		  	<groupId>org.springframework.boot</groupId>
		  	<artifactId>spring-boot-maven-plugin</artifactId>
		  	<version>2.2.5.RELEASE</version>
		  	<executions>
			  	<execution>
				  	<goals>
					  	<goal>repackage</goal>
				  	</goals>
			  	</execution>
		  	</executions>
	  	</plugin>
  	</plugins>
  </build>
           

(3)執行重新打包

~/Desktop/MyProject/springboot$ mvn package spring-boot:repackage
           

如果遇到異常:repackage failed: Source file must be provided,請參考《repackage failed: Source file must be provided異常》

3.spring-boot:build-info

根據目前MavenProject的内容生成build-info.properties檔案。

~/Desktop/MyProject/springboot$ mvn spring-boot:build-info
           

結果在target/classes目錄裡生成META-INF/build-info.properties:

~/Desktop/MyProject/springboot$ cd target
~/Desktop/MyProject/springboot/target$ tree
.
├── classes
│   ├── com
│   │   └── wong
│   │       ├── App.class
│   │       └── First.class
│   └── META-INF
│       └── build-info.properties
...
~/Desktop/MyProject/springboot/target$ cat classes/META-INF/build-info.properties
build.artifact=springboot
build.group=com.wong
build.name=springboot
build.time=2020-03-22T03\:35\:24.179Z
build.version=1.0.0

           

4.spring-boot:start 和 spring-boot:stop

繼續閱讀