Although Java does not allow you to express null safety in its type system, the Spring Framework now includes the following annotations in the org.springframework.lang package so that you can declare APIs and fields to be null safe:

  • @Nullable: An annotation indicating that a certain parameter, return value, or field may be null.

  • @NonNull: An annotation indicating that a particular parameter, return value, or field cannot be null (not needed for parameters/return values and fields where @NonNullApi annotations are applied) and @NonNullFields respectively).

  • @NonNullApi: A package-level annotation that declares a non-null value to be the default semantics for parameters and return values.

  • @NonNullFields: A package-level annotation that declares a non-null value to be the default semantics for fields.

The Spring Framework itself makes effective use of 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 for generic type arguments, varargs, and array elements is not yet supported, but should be added in a future release. For the latest information, see SPR-15942. Nullable variable declarations are expected to be refined between Spring Framework releases, including minor ones. The nullability of types used within a method body is outside the scope of this function.

Other common libraries, such as Reactor and Spring Data, contain null-safe APIs that use similar nullability organization, providing a consistent overall experience for developers applications on Spring.

Use examples

In addition to providing an explicit declaration of nullability to the Spring Framework API, these annotations can be used by IDEs (such as IDEA or Eclipse) to provide useful warnings related to null safety, thereby avoiding NullPointerException at runtime.

They are also used to make the Spring API null-safe in Kotlin projects, since Kotlin natively supports null-safety. More information can be found in the Kotlin support documentation.

JSR-305 Meta Annotations

Spring annotations are meta-annotated using annotations from JSR 305 (not implemented at the moment, but a widely used JSR). Meta annotations from JSR-305 allow tool vendors such as IDEA or Kotlin to provide support for null safety in a generic manner without having to hard code annotation support into Spring.

It is not necessary or recommended to add a JSR-305 dependency to your project's classpath to take advantage of Spring's null-safe API. Only for projects such as Spring-based libraries that use null-safety annotations in their codebase, you should add com.google.code.findbugs:jsr305:3.0.2 with the compileOnlyconfiguration from Gradle or scope provided from Maven to avoid compilation warnings.