Using `@Nullable` in the Spring Framework - JoseCanova/brainz GitHub Wiki

Using @Nullable in the Spring Framework

The Spring Framework provides the @Nullable annotation, located in the org.springframework.lang package, to explicitly declare that an annotated element (such as a parameter, return value, or field) can be null under certain circumstances.


Purpose and Usage

Null-Safety Declaration

  • Java's type system does not inherently enforce null-safety.
  • @Nullable offers a way to convey nullability information to developers and tools that support JSR-305.

Contextual Nullability

  • Particularly useful when the default nullability for a package or class is set to non-null (e.g., using @NonNullApi or @NonNullFields).
  • Allows specific elements to be explicitly marked as allowing null values.

Tooling Support

  • Tools such as IDEs and static analysis frameworks can leverage this annotation to provide warnings or errors related to potential NullPointerExceptions.

Kotlin Interoperability

  • Kotlin, which has built-in null-safety features, can infer nullability from Spring's @Nullable annotations, improving Java-Kotlin interoperability.

Where to Use

  • Method Parameters: To indicate that a method parameter can accept a null argument.
  • Method Return Values: To specify that a method might return null.
  • Fields: To declare that a class field can hold a null value.

Example Usage

import org.springframework.lang.Nullable;

public class ExampleService {

    // Field can be null
    @Nullable
    private String description;

    // Parameter can be null
    public void updateDescription(@Nullable String description) {
        this.description = description;
    }

    // Method may return null
    @Nullable
    public String getDescription() {
        return description;
    }
}

Tip:
Use @Nullable in combination with @NonNullApi or @NonNullFields for maximum clarity and safety in your codebase.