本指南向您展示如何使用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版本=“ 1.0”编码=“ 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>
    <模块>
        <module>库</ module>
        <module>应用</ module>
    </ modules>
</ project>
对于Gradle,您将需要一个settings.gradle包含相同目录的目录:
rootProject.name ='gs-multi-module' 包括“图书馆” 包括“申请”
并且(可选)您可以包括一个空白build.gradle(以帮助IDE识别根目录)。
创建目录结构
在要用作根目录的目录中,创建以下子目录结构(例如,mkdir library application在* nix系统上):
└──图书馆 └──申请
在项目的根目录中,您将需要建立一个构建系统,本指南将向您展示如何使用Maven或Gradle。
创建图书馆项目
这两个项目之一用作另一个项目(应用程序)将使用的库。
创建目录结构
在library目录中,创建以下子目录结构(例如,通过mkdir -p src/main/java/com/example/multimodule/service在* nix系统上使用):
└──src
    main──主要
        └──java
            └──com
                └──例子
                    └──多模块
                        └──服务
现在,您需要配置一个构建工具(Maven或Gradle)。在这两种情况下,请注意,库项目中根本没有使用Spring Boot插件。该插件的主要功能是创建一个可执行文件“über-jar”,而我们既不需要库又不需要库。
尽管未使用Spring Boot Maven插件,但您确实希望利用Spring Boot依赖项管理,因此可以通过使用spring-boot-starter-parentSpring Boot中的from作为父项目进行配置。一种替代方法是在文件的部分中将依赖性管理作为物料清单(BOM)导入。<dependencyManagement/>pom.xml
设置图书馆项目
对于Library项目,您无需添加依赖项。基本spring-boot-starter依赖关系提供了您所需的一切。
您可以直接从Spring Initializr获取具有必要依赖项的Maven构建文件。以下清单显示了pom.xml选择Maven时创建的文件:
<?xml版本=“ 1.0”编码=“ 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.boot </ groupId> <artifactId> spring-boot-starter-parent </ artifactId> <version> 2.4.3 </ version> <relativePath /> <!-从存储库中查找父级-> </ parent> <groupId> com.example </ groupId> <artifactId>多模块库</ artifactId> <version> 0.0.1-SNAPSHOT </ version> <名称>多模块库</名称> <description> Spring Boot的演示项目</ description> <属性> <java.version> 1.8 </java.version> </ properties> <依赖项> <依赖性> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter </ artifactId> </ dependency> <依赖性> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-test </ artifactId> <scope>测试</ scope> </ dependency> </ dependencies> <内部版本> <插件> <插件> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-maven-plugin </ artifactId> </ plugin> </ plugins> </ build> </ project>
您可以直接从Spring Initializr获取具有必要依赖项的Gradle构建文件。以下清单显示了build.gradle选择Gradle时创建的文件:
插件{
	id'org.springframework.boot'版本'2.4.3'
	id'io.spring.dependency-management'版本'1.0.11.RELEASE'
	id'java'
}
组='com.example'
版本='0.0.1-SNAPSHOT'
sourceCompatibility ='1.8'
储存库{
	mavenCentral()
}
依赖项{
	实现'org.springframework.boot:spring-boot-starter'
	testImplementation'org.springframework.boot:spring-boot-starter-test'
}
调整图书馆项目
如果您从中生成“库”项目,start.springref.com则该项目将包含构建系统的包装器脚本(mvnw或gradlew取决于您做出的选择)。您可以将该脚本及其关联的配置移至根目录:
$ mv mvnw* .mvn ..
$ mv gradlew* gradle ..
Library项目没有使用main方法的类(因为它不是应用程序)。因此,您必须告诉构建系统不要尝试为Library项目构建可执行的jar。(默认情况下,Spring Initializr会生成可执行项目。)
要告诉Maven不为Library项目构建可执行的jar,必须从pom.xmlSpring Initializr创建的代码块中删除以下代码块:
<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
  </plugins>
</build>
以下清单显示pom.xml了Library项目的最终文件:
<?xml版本=“ 1.0”编码=“ 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.boot </ groupId> <artifactId> spring-boot-starter-parent </ artifactId> <version> 2.4.3 </ version> <relativePath /> <!-从存储库中查找父级-> </ parent> <groupId> com.example </ groupId> <artifactId>库</ artifactId> <version> 0.0.1-SNAPSHOT </ version> <名称>多模块库</名称> <description> Spring Boot的演示项目</ description> <属性> <java.version> 1.8 </java.version> </ properties> <依赖项> <依赖性> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter </ artifactId> </ dependency> <依赖性> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-test </ artifactId> <scope>测试</ scope> </ dependency> </ dependencies> </ project>
要告诉Gradle不为Library项目构建可执行的jar,必须build.gradle在Spring Initializr创建的代码块中添加以下代码块:
bootJar {
  enabled = false
}
jar {
  enabled = true
}
该bootJar任务尝试创建一个可执行jar,这需要一个main()方法。结果,您需要禁用bootJar任务并启用jar任务(这将创建普通的jar而不是可执行的jar)。
以下清单显示build.gradle了Library项目的最终文件:
插件{
	id'org.springframework.boot'版本'2.4.3'
	id'io.spring.dependency-management'版本'1.0.11.RELEASE'
	id'java'
}
组='com.example'
版本='0.0.1-SNAPSHOT'
sourceCompatibility ='1.8'
储存库{
	mavenCentral()
}
bootJar {
	已启用=否
}
罐子{
	启用=真
}
依赖项{
	实现'org.springframework.boot:spring-boot-starter'
	testImplementation'org.springframework.boot:spring-boot-starter-test'
}
创建服务组件
该库将提供一个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 {
  }
}
在前面的清单中,我们service.message通过使用@SpringBootTest批注的默认属性为测试配置了。我们不建议放入application.properties库,因为在运行时与使用该库的应用程序可能会发生冲突(application.properties从类路径中仅加载了一个)。您可以放入application.properties测试类路径,但不能将其包括在jar中(例如,将其放入src/test/resources)。 | 
创建应用程序项目
Application项目使用Library项目,该项目提供了其他项目可以使用的服务。
创建目录结构
在application目录中,创建以下子目录结构(例如,mkdir -p src/main/java/com/example/multimodule/application在* nix系统上):
└──src
    main──主要
        └──java
            └──com
                └──例子
                    └──多模块
                        └──申请
除非要@ComponentScan在应用程序中将所有Spring组件包括在库中,否则请不要使用与库相同的包(或库包的父包)。
设置应用程序项目
对于Application项目,您需要Spring Web和Spring Boot Actuator依赖项。
您可以直接从Spring Initializr获取具有必要依赖项的Maven构建文件。以下清单显示了pom.xml选择Maven时创建的文件:
<?xml版本=“ 1.0”编码=“ 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.boot </ groupId> <artifactId> spring-boot-starter-parent </ artifactId> <version> 2.4.3 </ version> <relativePath /> <!-从存储库中查找父级-> </ parent> <groupId> com.example </ groupId> <artifactId>多模块应用程序</ artifactId> <version> 0.0.1-SNAPSHOT </ version> <名称>多模块应用程序</名称> <description> Spring Boot的演示项目</ description> <属性> <java.version> 1.8 </java.version> </ properties> <依赖项> <依赖性> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-actuator </ artifactId> </ dependency> <依赖性> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-web </ artifactId> </ dependency> <依赖性> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-test </ artifactId> <scope>测试</ scope> </ dependency> </ dependencies> <内部版本> <插件> <插件> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-maven-plugin </ artifactId> </ plugin> </ plugins> </ build> </ project>
您可以直接从Spring Initializr获取具有必要依赖项的Gradle构建文件。以下清单显示了build.gradle选择Gradle时创建的文件:
插件{
	id'org.springframework.boot'版本'2.4.3'
	id'io.spring.dependency-management'版本'1.0.11.RELEASE'
	id'java'
}
组='com.example'
版本='0.0.1-SNAPSHOT'
sourceCompatibility ='1.8'
储存库{
	mavenCentral()
}
依赖项{
	实现'org.springframework.boot:spring-boot-starter-actuator'
	实现'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
添加库依赖
Application项目需要依赖Library项目。您需要相应地修改您的应用程序构建文件。
对于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>2.4.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>multi-module-application</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>multi-module-application</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<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 '2.4.3'
	id 'io.spring.dependency-management' version '1.0.11.RELEASE'
	id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
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是不同的包(内部com.example.multimodule.application)比MyService(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创建了可重用的库,然后使用该库来构建应用程序。
也可以看看
以下指南也可能会有所帮助:
是否要编写新指南或为现有指南做出贡献?查看我们的贡献准则。
| 所有指南均以代码的ASLv2许可证和写作的Attribution,NoDerivatives创用CC许可证发布。 |