# 7. 空指针安全

尽管 Java 不允许您使用其类型系统来表达 null 安全性，但 Spring 框架现在在`org.springframework.lang`包中提供了以下注解，以便您声明 API 和字段的可空性：

* [`@Nullable`](https://docs.spring.io/spring-framework/docs/5.3.22/javadoc-api/org/springframework/lang/Nullable.html): 表示特定参数、返回值或字段可以是`null` 的注解。
* [`@NonNull`](https://docs.spring.io/spring-framework/docs/5.3.22/javadoc-api/org/springframework/lang/NonNull.html): 用于指示特定参数、返回值或字段不能出现`null`的注解（分别适用于`@NonNullApi`和 `@NonNullFields` 的参数、返回值和字段不需要）。
* [`@NonNullApi`](https://docs.spring.io/spring-framework/docs/5.3.22/javadoc-api/org/springframework/lang/NonNullApi.html): 包级别的注解，将非 null 声明为参数和返回值的默认语义。
* [`@NonNullFields`](https://docs.spring.io/spring-framework/docs/5.3.22/javadoc-api/org/springframework/lang/NonNullFields.html)：包级别的注解，将非空声明为字段的默认语义。

Spring 框架本身利用了这些注解，但它们也可以在任何基于 Spring 的 Java 项目中用于声明空安全 API 和可选的空安全字段。尚不支持泛型类型参数、可变参数和数组元素可空性，但应在即将发布的版本中提供， 有关最新信息，请参阅[SPR-15942 。](https://jira.spring.io/browse/SPR-15942)可空性声明预计将在 Spring Framework 版本之间进行微调，包括次要版本。方法体内使用的类型的可空性超出了此功能的范围。

其他常见的库，如 Reactor 和 Spring Data 提供了使用类似可空性安排的空安全 API，为 Spring 应用程序开发人员提供一致的整体体验。

#### 7.1. 用例

除了为 Spring Framework API 可空性提供显式声明之外，IDE（例如 IDEA 或 Eclipse）可以使用这些注解来提供与空安全性相关的有用警告，以避免在运行时报`NullPointerException`。

它们还用于在 Kotlin 项目中使 Spring API 为空安全，因为 Kotlin 原生支持[空安全](https://kotlinlang.org/docs/reference/null-safety.html)。[Kotlin 支持文档](https://docs.spring.io/spring-framework/docs/current/reference/html/languages.html#kotlin-null-safety)中提供了更多详细信息。

#### 7.2. JSR-305 元注解

Spring 注解使用[JSR 305](https://jcp.org/en/jsr/detail?id=305) 注解（一种休眠但广泛传播的 JSR）进行元注解。JSR-305 元注解让 IDEA 或 Kotlin 等工具供应商以通用方式提供空安全支持，而无需对 Spring 注解进行硬编码支持。

没有必要也不建议将 JSR-305 依赖项添加到项目类路径以利用 Spring 空安全 API。只有在代码库中使用空安全注解的基于 Spring 的库等项目才应添加 `com.google.code.findbugs:jsr305:3.0.2` 以及`compileOnly` Gradle 配置或 Maven `provided`的范围，以避免编译器警告。

###

###

###

####


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.shiker.tech/spring-he-xin-gong-neng/7.-kong-zhi-zhen-an-quan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
