Null-safety

Although Java does not let you express null-safety with its type system, the Spring Framework now provides the following annotations in the org.springframework.lang package to let you declare nullability of APIs and fields:

  • @Nullable: Annotation to indicate that a specific parameter, return value, or field can be null.

  • @NonNull: Annotation to indicate that a specific parameter, return value, or field cannot be null (not needed on parameters / return values and fields where @NonNullApi and @NonNullFields apply, respectively).

  • @NonNullApi: Annotation at the package level that declares non-null as the default semantics for parameters and return values.

  • @NonNullFields: Annotation at the package level that declares non-null as the default semantics for fields.

The Spring Framework itself leverages these annotations, but they can also be used in any Spring-based Java project to declare null-safe APIs and optionally null-safe fields. Generic type arguments, varargs and array elements nullability are not supported yet but should be in an upcoming release, see SPR-15942 for up-to-date information. Nullability declarations are expected to be fine-tuned between Spring Framework releases, including minor ones. Nullability of types used inside method bodies is outside of the scope of this feature.

Other common libraries such as Reactor and Spring Data provide null-safe APIs that use a similar nullability arrangement, delivering a consistent overall experience for Spring application developers.