[[null-safety]]
= Null-safety

Although Java does not allow to express null-safety with its type system, Spring Framework
now provides annotations to declare nullability of APIs and fields.

Spring Framework leverages itself these annotations, but they can also be used in any Spring based
Java project to declare null-safe APIs and optionally null-safe fields. Nullability of
types used inside method bodies is outside of the scope of this feature.

These annotations are meta-annotated with https://jcp.org/en/jsr/detail?id=305[JSR 305]
annotations (a dormant JSR but supported by tools like IntelliJ IDEA) to provide useful
warnings to Java developers related to null-safety in order to avoid `NullPointerException`
at runtime. JSR 305 meta-annotations allows tooling vendors to provide null-safety support
in a generic way, without having to hard-code support for Spring annotations.

[NOTE]
====
It is not necessary with Kotlin 1.1.5+ nor recommanded to have JSR 305 dependency in user
project classpath.
====

They are also used by Kotlin which supports natively
https://kotlinlang.org/docs/reference/null-safety.html[null-safety]. More details are
available in <<kotlin#null-safety,Kotlin support documentation>>.

[NOTE]
====
Other libraries like Reactor or Spring Data leverage these annotations as well to provide
null-safe APIs.
====

The following annotations are provided in the `org.springframework.lang` package:

 * {api-spring-framework}/lang/NonNull.html[`@NonNull`] annotation where specific parameter,
 return value or field cannot be `null` (not needed on parameter and return value
 where `@NonNullApi` and `@NonNullFields` apply) .
 * {api-spring-framework}/lang/Nullable.html[`@Nullable`] annotation where specific
 parameter, return value or field can be `null`.
 * {api-spring-framework}/lang/NonNullApi.html[`@NonNullApi`] annotation at package level
 declares non-null as the default behavior for parameters and return values.
 * {api-spring-framework}/lang/NonNullFields.html[`@NonNullFields`] annotation at package
 level declares non-null as the default behavior for fields.

[NOTE]
====
Generic type arguments, varargs and array elements nullability are not supported yet,
see https://jira.spring.io/browse/SPR-15942[SPR-15942] for up-to-date information.
====