原文:Spring 官方入门指南 Accessing Data with MongoDB。作者署名:Spring 团队(页面无个人署名)。本文经授权译写,并对原页中与当前代码不一致的说明作了标明的订正。
这份指南带你使用 Spring Data MongoDB 创建一个应用,将数据保存到 MongoDB,再把它读回来。MongoDB 是文档数据库;本例中需要保存的是 Customer 普通 Java 对象,也就是 POJO。重点是对象与文档如何映射、仓储接口怎样生成查询,以及 Spring Boot 如何把这些部分连接起来。
准备工具与选择起点
原指南预计需要约 15 分钟,准备熟悉的文本编辑器或 IDE,并使用 Java 17 或更新版本。页面列出的构建工具下限是 Gradle 7.5+ 或 Maven 3.5+,也可直接导入 Spring Tool Suite、IntelliJ IDEA 或 VS Code。
版本核验:指南是滚动更新页面。2026 年 10 月 5 日从官方示例仓库读取的 complete/pom.xml 使用 Spring Boot 4.0.8,Java 配置为 17。原页上较旧的构建工具下限不能作为 Boot 4 项目的兼容保证;请使用仓库随附的 Maven/Gradle wrapper,并核对所选 Spring Boot 版本的系统要求。本文保留当前页面中的 JSpecify Nullable 与 ApplicationRunner 写法,不混用旧版教程代码。
Boot 4.0.8 官方系统要求列出 Maven 3.6.3 或更新版本,以及 Gradle 8.x(至少 8.14)或 9.x;因此不要沿用页面中较低的旧版下限。
你可以从头完成每个步骤,也可以直接从官方仓库的初始项目开始。如果选择后者,先下载并解压示例仓库,或者克隆:
git clone https://github.com/spring-guides/gs-accessing-data-mongodb.git
cd gs-accessing-data-mongodb/initial
随后直接进入 MongoDB 安装部分。完成后,可以对照同一仓库的 complete 目录检查项目结构与代码。
用 Spring Initializr 创建项目
从头开始时,打开 Spring Initializr。这个服务会生成项目的基本结构,并配置所选依赖。
- 选择 Gradle 或 Maven;本指南的编程语言选择 Java。
- 在 Dependencies 中添加 Spring Data MongoDB 和 Testcontainers。
- 点击 Generate,下载并解压 ZIP 文件,再用 IDE 打开项目。
如果 IDE 集成了 Spring Initializr,也可以在 IDE 中完成这些步骤。另一个选择是 fork 官方仓库,再在编辑器中打开。原页把生成结果称为“web application”,但本指南的主要代码是启动时执行数据库操作的应用,未提供 HTTP 控制器;只有引入相应 Web 依赖并编写接口,才会得到对外的 Web 功能。
安装并启动 MongoDB
运行本例前,需要有可连接的 MongoDB 服务。原文以装有 Homebrew 的 macOS 为例:
brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-community
前两条命令添加 MongoDB 的 Homebrew 源并安装软件;最后一条会在本机启动服务。它们会改变本机环境,不是只读检查命令。其他操作系统或安装方式请参考 MongoDB 安装文档。安装后,可以在另一个终端运行 mongosh 启动 MongoDB 命令行客户端。
数据边界:为本教程准备独立的演示数据库,确认连接目标后再运行应用。后面的原版示例含有 deleteAll(),每次启动都会清空 Customer 所映射的集合。不要把演示程序连接到存有实际客户数据的数据库。

定义一个简单的实体
MongoDB 按文档保存数据。本例用 Customer 表示客户。创建 src/main/java/com/example/accessingdatamongodb/Customer.java:
package com.example.accessingdatamongodb;
import org.jspecify.annotations.Nullable;
import org.springframework.data.annotation.Id;
public class Customer {
@Id
public @Nullable String id;
public String firstName;
public String lastName;
public Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format(
"Customer[id=%s, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
Customer 有 id、firstName 和 lastName 三个属性。id 主要供 MongoDB 标识文档使用;@Id 告诉 Spring Data MongoDB 哪个字段是文档标识。Nullable 表示在对象尚未保存等情况下,id 可以为空。
两个构造方法分别用于无参实例化与方便地创建待保存客户。原指南为演示提供无参构造方法,但这不意味着 Spring Data 的所有映射场景都必须有无参构造方法。为保持代码简洁,本例没有编写常见的 getter 和 setter。
firstName 和 lastName 没有额外注解,默认映射到文档中同名的字段。toString() 用于把客户信息打印出来。MongoDB 以集合组织文档,Spring Data MongoDB 默认把 Customer 映射到名为 customer 的集合;如果想使用其他集合名,可以在类上添加 @Document 注解并配置名称。
声明仓储接口,让 Spring Data 生成查询
Spring Data MongoDB 负责持久化 MongoDB 数据,也继承了 Spring Data Commons 提供的查询派生能力。对于本例这样的简单查询,你只需声明方法,不必手写 MongoDB 查询语句。
创建 src/main/java/com/example/accessingdatamongodb/CustomerRepository.java:
package com.example.accessingdatamongodb;
import java.util.List;
import org.jspecify.annotations.Nullable;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CustomerRepository extends MongoRepository<Customer, String> {
@Nullable
Customer findByFirstName(String firstName);
List<Customer> findByLastName(String lastName);
}
MongoRepository 的两个类型参数分别是要管理的对象类型 Customer,以及标识类型 String。接口已经提供创建、读取、更新和删除等常见 CRUD 操作。
findByFirstName 会根据 firstName 属性查找客户;findByLastName 则根据 lastName 返回客户列表。Spring Data 在应用运行时创建仓储代理,你无需再手写 CustomerRepository 的实现类。
查询语义补充:findByFirstName 的单对象返回类型表达的是“至多一个结果”的约定,不是自动为 firstName 建立唯一约束。示例只有一个 Alice,所以可以这样演示;如果实际数据允许重名,应根据业务改用 List<Customer> 或其他合适的查询结果形式,而不能假设它总会随意挑选第一条。未匹配时则允许返回 null。
创建启动类
Initializr 生成的基础启动类位于 src/main/java/com/example/accessingdatamongodb/AccessingDataMongodbApplication.java:
package com.example.accessingdatamongodb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AccessingDataMongodbApplication {
public static void main(String[] args) {
SpringApplication.run(AccessingDataMongodbApplication.class, args);
}
}
@SpringBootApplication 汇集了几类常用配置能力:
- 配置类能力:将该类作为应用上下文的 bean 定义来源。
- 自动配置:根据 classpath、已有 bean 和属性设置补充配置。例如,存在相应 Spring MVC 依赖时,可启用 Web 应用相关配置,包括 DispatcherServlet。
- 组件扫描:默认从启动类所在包及其子包中发现组件。本例的根包是 com.example.accessingdatamongodb,不能把原页笼统写的 com/example 理解成任意父包都会被自动扫描。
main() 通过 SpringApplication.run() 启动应用,不需要 XML 或 web.xml。仓储接口只要处于启动类同包或子包中,就能由相应自动配置发现;如果需要更精确地控制仓储扫描,可使用 @EnableMongoRepositories。
@EnableMongoRepositories 默认扫描所在包中的 Spring Data 仓储接口。当项目分包使接口不在扫描范围内时,可以使用 basePackageClasses = MyRepository.class,通过类型安全的方式指定扫描根包。
仓储的 find* 方法底层由 MongoTemplate 执行查询。更复杂的场景也可以直接使用 MongoTemplate,但那超出了本指南的范围,可继续查阅 Spring Data MongoDB 参考文档。
写入数据并查看查询结果
把启动类替换为下面的完成版。它声明一个 ApplicationRunner bean,由容器向 runner 方法注入 CustomerRepository。
运行前务必确认:下面保留了原文的 repository.deleteAll()。它不是只删除 Alice 和 Bob,而是删除该仓储管理集合中的全部文档,且应用每次启动都会再次执行。这里是为了得到可重复的教学数据;实际应用应删除这段演示初始化逻辑,或把整段 runner 限定在独立演示配置和专用数据库中。
package com.example.accessingdatamongodb;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class AccessingDataMongodbApplication {
public static void main(String[] args) {
SpringApplication.run(AccessingDataMongodbApplication.class, args);
}
@Bean
ApplicationRunner runner(CustomerRepository repository) {
return args -> {
// 原文操作:清空 customer 集合;仅用于专用演示数据库。
repository.deleteAll();
repository.save(new Customer("Alice", "Smith"));
repository.save(new Customer("Bob", "Smith"));
System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : repository.findAll()) {
System.out.println(customer);
}
System.out.println();
System.out.println("Customer found with findByFirstName('Alice'):");
System.out.println("--------------------------------");
System.out.println(repository.findByFirstName("Alice"));
System.out.println("Customers found with findByLastName('Smith'):");
System.out.println("--------------------------------");
for (Customer customer : repository.findByLastName("Smith")) {
System.out.println(customer);
}
};
}
}
Spring Data MongoDB 会动态创建仓储代理并注入 runner。代码先保存 Alice Smith 和 Bob Smith,再通过 findAll() 读取所有客户,使用 findByFirstName("Alice") 查找 Alice,最后用 findByLastName("Smith") 读取所有姓 Smith 的客户。
Spring Boot 在默认配置下尝试连接本机 MongoDB。需要连接其他服务器时,应按所选版本的 MongoDB 配置参考设置地址、数据库及凭据,不要把生产连接信息直接写进示例源码。
构建并运行可执行 JAR
你可以通过 Gradle 或 Maven 直接运行,也可以把类、依赖和资源打包成一个可执行 JAR,便于在不同环境中交付、版本管理和部署。
使用 Gradle:
./gradlew bootRun
# 或先构建,再运行
./gradlew build
java -jar build/libs/gs-accessing-data-mongodb-0.0.1-SNAPSHOT.jar
使用 Maven:
./mvnw spring-boot:run
# 或先构建,再运行
./mvnw clean package
java -jar target/gs-accessing-data-mongodb-0.0.1-SNAPSHOT.jar
这些是原页的命令与文件名。生成的 JAR 名称取决于项目设置:本次核验的 complete/pom.xml 的 artifactId 是 accessing-data-mongodb-complete,不能保证生成文件叫 gs-accessing-data-mongodb-0.0.1-SNAPSHOT.jar。请先查看 build/libs 或 target 下的实际产物,再替换命令中的文件名。Windows 原生终端应使用对应的 gradlew.bat 或 mvnw.cmd。构建会写入产物,clean 会清理构建输出,运行应用还会触发前述数据库删除与写入。
原文订正:页面最后仍说应用“实现 CommandLineRunner,自动调用 run 方法”,但展示的当前代码实际声明了 ApplicationRunner bean。两者都可在启动过程中执行逻辑;本文按页面代码解释为 ApplicationRunner,而不是声称这个类实现了 CommandLineRunner。
原文给出的示例输出如下。这里的 ID 是原文样例,并非本次运行产生;你的 ID 和行顺序可能不同:
Customers found with findAll():
-------------------------------
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
Customer[id=51df1b0a3004cb49c50210f9, firstName='Bob', lastName='Smith']
Customer found with findByFirstName('Alice'):
--------------------------------
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
Customers found with findByLastName('Smith'):
--------------------------------
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
Customer[id=51df1b0a3004cb49c50210f9, firstName='Bob', lastName='Smith']
完成之后
至此,你已经了解如何启动 MongoDB,用 Spring Data MongoDB 保存普通 Java 对象,并通过仓储接口把文档读回来,而无需编写具体的仓储实现类。若希望在仓储外提供支持超媒体的 REST 接口,可接着阅读 Accessing MongoDB Data with REST。原文还推荐了 JPA、GemFire、MySQL 与 Neo4j 数据访问指南,作为其他存储方案的延伸阅读。
静态审查范围:本文核对了完整指南与官方 POM,未安装 MongoDB、未运行构建、未连接数据库,也未执行任何示例。Testcontainers 是 Initializr 推荐添加的依赖,不能仅凭出现这个依赖就认为本文已经进行了容器测试。生产使用还需单独设计认证、索引、数据持久化、连接参数和查询基数约束。
许可说明:原指南代码采用 Apache License 2.0,文字采用 CC BY-ND 3.0。原文版权 © 2005–2026 Broadcom,作者署名 Spring 团队。保留原文公开许可,不把 ND 本身解释为授予翻译权;编辑增补与自绘图已标明。
原代码的 Apache License 2.0
Spring 指南示例代码;本文翻译和编校变更于 2026-10-05 标注,原代码与替代建议分别列示。
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
原指南文字许可声明
此为官方 LICENSE.writing.txt 的原文声明;许可全文见上方 CC BY-ND 3.0 链接。
Except where otherwise noted, this work is licensed under https://creativecommons.org/licenses/by-nd/3.0/












暂无评论内容