创建多模块项目

本指南向您展示如何使用 Spring Boot 创建一个多模块项目。该项目将包含一个库 Jar 包和一个使用该库的主应用程序。您也可以使用它来了解如何单独构建一个库(即,不是应用程序的 Jar 文件)。

您将构建什么

您将设置一个库 Jar 包,该 Jar 包提供一个用于简单“Hello, World”消息的服务,然后将该服务包含在一个使用该库作为依赖项的 Web 应用程序中。

你需要什么

如何完成本指南

与大多数 Spring 入门指南一样,您可以从头开始并完成每个步骤,也可以跳过您已熟悉的基本设置步骤。无论哪种方式,您最终都会得到可工作的代码。

要从头开始,请继续阅读创建根项目

跳过基础知识,请执行以下操作

完成后,您可以将结果与 gs-multi-module/complete 中的代码进行比较。

首先,您需要设置一个基本的构建脚本。在使用 Spring 构建应用程序时,您可以使用任何您喜欢的构建系统,但这里包含了与 GradleMaven 协作所需的代码。如果您不熟悉其中任何一个,请参阅 使用 Gradle 构建 Java 项目使用 Maven 构建 Java 项目

创建根项目

本指南将引导您构建两个项目,其中一个项目是另一个项目的依赖项。因此,您需要在根项目下创建两个子项目。但首先,在顶层创建构建配置。对于 Maven,您需要一个 pom.xml,其中 <modules> 列出了子目录

<?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 插件在库项目中完全没有使用。该插件的主要功能是创建一个可执行的“über-jar”,而我们既不需要也不想要一个库。

尽管没有使用 Spring Boot Maven 插件,但您确实希望利用 Spring Boot 依赖管理,因此通过使用 Spring Boot 的 spring-boot-starter-parent 作为父项目来配置它。另一种方法是将依赖管理作为物料清单 (BOM) 导入到 pom.xml 文件的 <dependencyManagement/> 部分。

设置库项目

对于库项目,您无需添加依赖项。基本的 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 ..

最好是库依赖于最窄的依赖项,而不是启动器。对于我们自己的使用,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 注解的默认属性为测试配置了 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'
}

编写应用程序

应用程序中的主类可以是一个 @RestController,它使用库中的 Service 来呈现消息。以下列表(来自 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 位于与 MyService (com.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 许可,文字内容采用署名-禁止演绎知识共享许可

获取代码