创建多模块项目

本指南向您展示如何使用 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 或使用命令行启动应用程序。应用程序运行后,在浏览器中访问客户端应用程序,地址为http://localhost:8080/。在那里,您应该在响应中看到Hello, World

如果您使用 Gradle,以下命令(实际上是按顺序运行的两个命令)将首先构建库,然后运行应用程序

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

如果您使用 Maven,以下命令(实际上是按顺序运行的两个命令)将首先构建库,然后运行应用程序

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

总结

恭喜!您已使用 Spring Boot 创建了一个可重用库,然后使用该库构建了一个应用程序。

另请参阅

以下指南可能也有帮助

想撰写新的指南或为现有指南贡献内容?请查阅我们的贡献指南

所有指南的代码均采用 ASLv2 许可发布,文字内容采用署名-禁止演绎创作共用许可

获取代码