本指南将向您展示如何使用 Spring Boot 创建一个多模块项目。该项目将包含一个库 jar 和一个使用该库的主应用程序。您还可以通过它了解如何单独构建一个库(即不是应用程序的 jar 文件)。
您将构建什么
您将设置一个库 jar,该库暴露一个用于简单“Hello, World”消息的服务,然后将该服务包含在一个使用该库作为依赖项的 Web 应用程序中。
你需要准备
如何完成本指南
与大多数 Spring 入门指南 一样,您可以从头开始并完成每个步骤,也可以跳过您已经熟悉的基本设置步骤。无论哪种方式,您最终都能获得可运行的代码。
要从头开始,请继续创建根项目。
要跳过基础步骤,请执行以下操作:
-
下载并解压本指南的源代码仓库,或者使用 Git 克隆它:
git clone https://github.com/spring-guides/gs-multi-module.git
-
进入
gs-multi-module/initial
目录 -
跳转到 创建库项目。
完成后,您可以将结果与 gs-multi-module/complete
中的代码进行对比。
首先,您需要设置一个基本的构建脚本。在使用 Spring 构建应用程序时,您可以使用任何喜欢的构建系统,但这里包含了使用 Gradle 和 Maven 所需的代码。如果您对两者都不熟悉,请参考 使用 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
作为父项目来进行配置。另一种方法是在 pom.xml
文件的 <dependencyManagement/>
部分中作为物料清单 (BOM) 导入依赖管理。
设置库项目
对于 Library 项目,您无需添加依赖项。基本的 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
生成了 Library 项目,它将包含构建系统的包装脚本(mvnw
或 gradlew
,取决于您所做的选择)。您可以将该脚本及其相关配置移动到根目录中:
$ 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>
以下清单展示了 Library 项目的最终 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 不为 Library 项目构建可执行的 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")
}
以下清单展示了 Library 项目的最终 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'
}
编写应用程序
应用程序中的主类可以是一个 @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.application
和 com.example.multimodule.service
),@SpringBootApplication
无法自动检测到它。有多种方法可以让 MyService
被扫描到:
-
直接使用
@Import(MyService.class)
导入。 -
使用
@SpringBootApplication(scanBasePackageClasses={…})
从其包中获取所有内容。 -
通过名称指定父包:
com.example.multimodule
。(本指南使用此方法)
如果您的应用程序也使用了 JPA 或 Spring Data,
@EntityScan
和@EnableJpaRepositories
(及相关)注解在没有明确指定的情况下,只会从@SpringBootApplication
继承它们的基础包。也就是说,一旦您指定了scanBasePackageClasses
或scanBasePackages
,您可能还需要显式地使用@EntityScan
和@EnableJpaRepositories
,并明确配置它们的包扫描。
创建 application.properties 文件
您需要在 application.properties
中为库中的服务提供一条消息。在源码目录中,您需要创建一个名为 src/main/resources/application.properties
的文件。以下清单展示了一个可行的文件内容:
service.message=Hello, World
测试应用程序
通过启动应用程序来测试端到端的结果。您可以在 IDE 中启动应用程序,也可以使用命令行。一旦应用程序运行起来,请在浏览器中访问客户端应用程序,网址为 http://localhost:8080/
。在那里,您应该会看到响应中显示 Hello, World
。
如果您使用 Gradle,以下命令(实际上是按顺序运行的两个命令)将首先构建库,然后运行应用程序:
$ ./gradlew build && ./gradlew :application:bootRun
如果您使用 Maven,以下命令(实际上是依次运行的两个命令)将首先构建库,然后运行应用程序:
$ ./mvnw install && ./mvnw spring-boot:run -pl application
总结
恭喜!您已经使用 Spring Boot 创建了一个可重用的库,并使用该库构建了一个应用程序。
另请参阅
以下指南可能也会有所帮助: