建立多模組專案

本指南向您展示如何使用 Spring Boot 建立多模組專案。該專案將包含一個庫 jar 和一個使用該庫的主應用程式。您也可以使用它來了解如何單獨構建一個庫(即非應用程式的 jar 檔案)。

您將構建什麼

您將設定一個庫 jar,該 jar 暴露一個服務用於簡單的“Hello, World”訊息,然後將該服務包含在一個使用該庫作為依賴項的 Web 應用程式中。

您需要什麼

如何完成本指南

與大多數 Spring 入門指南一樣,您可以從頭開始並完成每個步驟,也可以跳過您已經熟悉的基本設定步驟。無論哪種方式,您最終都會得到可用的程式碼。

從頭開始,請轉到建立根專案

跳過基礎知識,請執行以下操作

完成時,您可以對照gs-multi-module/complete中的程式碼檢查結果。

首先,您需要設定一個基本的構建指令碼。使用 Spring 構建應用程式時,您可以使用任何喜歡的構建系統,但此處包含了使用GradleMaven所需的程式碼。如果您對它們都不熟悉,請參閱使用 Gradle 構建 Java 專案使用 Maven 構建 Java 專案

建立根專案

本指南將介紹構建兩個專案,其中一個專案是另一個專案的依賴項。因此,您需要在根專案下建立兩個子專案。但首先,在頂層建立構建配置。對於 Maven,您需要一個包含列出子目錄的<modules>塊的pom.xml檔案

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-multi-module</artifactId>
    <version>0.1.0</version>
    <packaging>pom</packaging>

    <modules>
        <module>library</module>
        <module>application</module>
    </modules>

</project>

對於 Gradle,您需要一個包含相同目錄的settings.gradle檔案

rootProject.name = 'gs-multi-module'

include 'library'
include 'application'

並且(可選)您可以包含一個空的build.gradle檔案(以幫助 IDE 識別根目錄)。

建立目錄結構

在您希望作為根目錄的目錄下,建立以下子目錄結構(例如,在 *nix 系統上使用mkdir library application

└── library
└── application

在專案的根目錄下,您需要設定一個構建系統,本指南將向您展示如何使用 Maven 或 Gradle。

建立庫專案

這兩個專案中的一個將充當庫,供另一個專案(應用程式)使用。

建立目錄結構

library目錄下,建立以下子目錄結構(例如,在 *nix 系統上使用mkdir -p src/main/java/com/example/multimodule/service

└── src
    └── main
        └── java
            └── com
                └── example
                    └── multimodule
                        └── service

現在您需要配置一個構建工具(Maven 或 Gradle)。在這兩種情況下,請注意 Spring Boot 外掛在庫專案中完全不使用。該外掛的主要功能是建立一個可執行的“uber-jar”,而這對於庫來說既不需要也不想要。

儘管未使用 Spring Boot Maven 外掛,但您確實希望利用 Spring Boot 依賴管理,因此將其配置為使用 Spring Boot 的spring-boot-starter-parent作為父專案。另一種方法是在pom.xml檔案的<dependencyManagement/>部分將依賴管理作為材料清單(BOM)匯入。

設定庫專案

對於庫專案,您無需新增太多依賴項。基本的spring-boot-starter依賴項提供了您所需的一切。

您可以直接從Spring Initializr獲取包含所需依賴項的 Maven 構建檔案。以下列表顯示了選擇 Maven 時建立的pom.xml檔案

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.3.0</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>library</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>library</name>
	<description>Demo project for Spring Boot</description>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

您可以直接從Spring Initializr獲取包含所需依賴項的 Gradle 構建檔案。以下列表顯示了選擇 Gradle 時建立的build.gradle檔案

plugins {
	id 'org.springframework.boot' version '3.3.0'
	id 'io.spring.dependency-management' version '1.1.5'
	id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
  sourceCompatibility = '17'
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

調整庫專案

如果您從start.spring.io生成了庫專案,它將包含一個用於構建系統的包裝指令碼(取決於您的選擇,可能是mvnwgradlew)。您可以將該指令碼及其相關配置移至根目錄

$ mv mvnw* .mvn ..
$ mv gradlew* gradle ..

最好讓庫依賴於最窄的依賴項,而不是一個 starter。對於我們自己的使用,org.springframework.boot:spring-boot包含了我們需要的所有程式碼。移除現有條目中的-starter可確保庫不會引入太多依賴項。

庫專案沒有包含 main 方法的類(因為它不是應用程式)。因此,您必須告訴構建系統不要嘗試為庫專案構建可執行 jar。(預設情況下,Spring Initializr 構建可執行專案。)

要告訴 Maven 不要為庫專案構建可執行 jar,您必須從 Spring Initializr 建立的pom.xml中刪除以下塊

<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
  </plugins>
</build>

以下列表顯示了庫專案的最終pom.xml檔案

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.2.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>library</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>library</name>
	<description>Demo project for Spring Boot</description>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

</project>

要告訴 Gradle 不要為庫專案構建可執行 jar,您必須將以下塊新增到 Spring Initializr 建立的build.gradle

plugins {
  id 'org.springframework.boot' version '3.2.2' apply false
  id 'io.spring.dependency-management' version '1.1.4'
  // ... other plugins
}

dependencyManagement {
  imports {
    mavenBom org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES
  }
}

bootJar任務嘗試建立可執行 jar,這需要一個main()方法。因此,您需要透過停用 Spring Boot 外掛來停用它,同時保留其依賴管理功能。

此外,現在我們已停用 Spring Boot 外掛,它不再自動配置JavaCompiler任務以啟用-parameters選項。如果您使用引用引數名稱的表示式,這一點很重要。以下配置啟用此選項

tasks.withType(JavaCompile).configureEach {
  options.compilerArgs.add("-parameters")
}

以下列表顯示了庫專案的最終build.gradle檔案

plugins {
	id 'org.springframework.boot' version '3.3.0' apply false
	id 'io.spring.dependency-management' version '1.1.5'
	id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
  sourceCompatibility = '17'
}

repositories {
	mavenCentral()
}

dependencyManagement {
	imports {
		mavenBom org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES
	}
}

dependencies {
	implementation 'org.springframework.boot:spring-boot'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.withType(JavaCompile).configureEach {
	options.compilerArgs.add("-parameters")
}

建立服務元件

該庫將提供一個可供應用程式使用的MyService類。以下列表(來自library/src/main/java/com/example/multimodule/service/MyService.java)顯示了MyService

package com.example.multimodule.service;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

@Service
@EnableConfigurationProperties(ServiceProperties.class)
public class MyService {

  private final ServiceProperties serviceProperties;

  public MyService(ServiceProperties serviceProperties) {
    this.serviceProperties = serviceProperties;
  }

  public String message() {
    return this.serviceProperties.getMessage();
  }
}

為了以標準的 Spring Boot 方式(使用application.properties)使其可配置,您還可以新增一個@ConfigurationProperties類。ServiceProperties類(來自library/src/main/java/com/example/multimodule/service/ServiceProperties.java)滿足了這一需求

package com.example.multimodule.service;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("service")
public class ServiceProperties {

  /**
   * A message for the service.
   */
  private String message;

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }
}

您不必非得這樣做。一個庫可能只提供純 Java API,而不包含任何 Spring 特性。在這種情況下,使用該庫的應用程式將需要自行提供配置。

測試服務元件

您會希望為您的庫元件編寫單元測試。如果您作為庫的一部分提供了可重用的 Spring 配置,您可能還需要編寫一個整合測試,以確保配置有效。為此,您可以使用 JUnit 和@SpringBootTest註解。以下列表(來自library/src/test/java/com/example/multimodule/service/MyServiceTest.java)顯示瞭如何這樣做

package com.example.multimodule.service;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest("service.message=Hello")
public class MyServiceTest {

  @Autowired
  private MyService myService;

  @Test
  public void contextLoads() {
    assertThat(myService.message()).isNotNull();
  }

  @SpringBootApplication
  static class TestConfiguration {
  }

}
在前面的列表中,我們透過使用@SpringBootTest註解的 default 屬性為測試配置了service.message。我們建議將application.properties放在庫中,因為在執行時可能與使用該庫的應用程式發生衝突(類路徑中只加載一個application.properties)。您可以application.properties放在測試類路徑中,但不將其包含在 jar 中(例如,將其放在src/test/resources中)。

建立應用程式專案

應用程式專案使用了庫專案,該庫專案提供了一個其他專案可以使用的服務。

建立目錄結構

application目錄下,建立以下子目錄結構(例如,在 *nix 系統上使用mkdir -p src/main/java/com/example/multimodule/application

└── src
    └── main
        └── java
            └── com
                └── example
                    └── multimodule
                        └── application

除非您希望透過應用程式中的@ComponentScan包含庫中的所有 Spring 元件,否則不要使用與庫相同的包(或庫包的父包)。

設定應用程式專案

對於應用程式專案,您需要 Spring Web 和 Spring Boot Actuator 依賴項。

您可以直接從Spring Initializr獲取包含所需依賴項的 Maven 構建檔案。以下列表顯示了選擇 Maven 時建立的pom.xml檔案

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.3.0</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>application</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>application</name>
	<description>Demo project for Spring Boot</description>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

您可以直接從Spring Initializr獲取包含所需依賴項的 Gradle 構建檔案。以下列表顯示了選擇 Gradle 時建立的build.gradle檔案

plugins {
	id 'org.springframework.boot' version '3.3.0'
	id 'io.spring.dependency-management' version '1.1.5'
	id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
	sourceCompatibility = '17'
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-actuator'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

您可以刪除mvnw和/或gradlew包裝器及其相關配置檔案

$ rm -rf mvnw* .mvn
$ rm -rf gradlew* gradle

新增庫依賴項

應用程式專案需要依賴庫專案。您需要相應地修改應用程式構建檔案。

對於 Maven,新增以下依賴項

<dependency>
  <groupId>com.example</groupId>
  <artifactId>library</artifactId>
  <version>${project.version}</version>
</dependency>

以下列表顯示了最終的pom.xml檔案

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.3.0</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>application</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>application</name>
	<description>Demo project for Spring Boot</description>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>com.example</groupId>
			<artifactId>library</artifactId>
			<version>${project.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

對於 Gradle,新增以下依賴項

implementation project(':library')

以下列表顯示了最終的build.gradle檔案

plugins {
	id 'org.springframework.boot' version '3.3.0'
	id 'io.spring.dependency-management' version '1.1.5'
	id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
	sourceCompatibility = '17'
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-actuator'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation project(':library')
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

編寫應用程式

應用程式中的主類可以是使用庫中Service來渲染訊息的@RestController。以下列表(來自application/src/main/java/com/example/multimodule/application/DemoApplication.java)顯示了這樣一個類

package com.example.multimodule.application;

import com.example.multimodule.service.MyService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication(scanBasePackages = "com.example.multimodule")
@RestController
public class DemoApplication {

  private final MyService myService;

  public DemoApplication(MyService myService) {
    this.myService = myService;
  }

  @GetMapping("/")
  public String home() {
    return myService.message();
  }

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

@SpringBootApplication是一個便捷註解,它包含了以下所有註解

  • @Configuration:將類標記為應用程式上下文的 bean 定義源。

  • @EnableAutoConfiguration:告訴 Spring Boot 根據類路徑設定、其他 bean 和各種屬性設定開始新增 bean。例如,如果類路徑中有spring-webmvc,則此註解將應用程式標記為 web 應用程式並激活關鍵行為,例如設定DispatcherServlet

  • @ComponentScan:告訴 Spring 在com/example包中查詢其他元件、配置和服務,以便找到控制器。

main()方法使用 Spring Boot 的SpringApplication.run()方法來啟動應用程式。您注意到沒有一行 XML 嗎?也沒有web.xml檔案。這個 web 應用程式是 100% 純 Java,您無需處理任何底層或基礎設施的配置。

由於DemoApplication位於與MyServicecom.example.multimodule.service)不同的包(com.example.multimodule.application)中,@SpringBootApplication無法自動檢測到它。有幾種不同的方法可以讓MyService被載入

  • 使用@Import(MyService.class)直接匯入。

  • 使用@SpringBootApplication(scanBasePackageClasses={…​})從其包中獲取所有內容。

  • 按名稱指定父包:com.example.multimodule。(本指南使用此方法)

如果您的應用程式也使用 JPA 或 Spring Data,則@EntityScan@EnableJpaRepositories(以及相關)註解在未明確指定時僅從@SpringBootApplication繼承其基本包。也就是說,一旦您指定了scanBasePackageClassesscanBasePackages,您可能還需要明確使用@EntityScan@EnableJpaRepositories並明確配置其包掃描。

建立application.properties檔案

您需要在application.properties中為庫中的服務提供一條訊息。在原始檔夾中,您需要建立一個名為src/main/resources/application.properties的檔案。以下列表顯示了一個可以使用的檔案

service.message=Hello, World

測試應用程式

透過啟動應用程式來測試端到端結果。您可以在 IDE 或使用命令列啟動應用程式。應用程式執行後,在瀏覽器中訪問客戶端應用程式,地址為https://:8080/。在那裡,您應該在響應中看到Hello, World

如果您使用 Gradle,以下命令(實際上是按順序執行的兩個命令)將首先構建庫,然後執行應用程式

$ ./gradlew build && ./gradlew :application:bootRun

如果您使用 Maven,以下命令(實際上是按順序執行的兩個命令)將首先構建庫,然後執行應用程式

$ ./mvnw install && ./mvnw spring-boot:run -pl application

總結

恭喜!您已使用 Spring Boot 建立了一個可重用庫,然後使用該庫構建了一個應用程式。

另請參閱

以下指南可能也有幫助

想撰寫新的指南或為現有指南貢獻內容?請查閱我們的貢獻指南

所有指南的程式碼均採用 ASLv2 許可釋出,文字內容採用署名-禁止演繹創作共用許可

獲取程式碼