Null-safety (Spring Boot)

Introduction

@NonNullApi and @NonNullFields are package level Spring annotations that define the default behaviour:


References

Spring Null-Safety Annotations

https://www.baeldung.com/spring-null-safety-annotations

Which @NotNull Java annotation should I use?

https://stackoverflow.com/a/42695253/1323562

When to Use JSR 305 for Nullability in Java

https://dzone.com/articles/when-to-use-jsr-305-for-nullability-in-java



Considerations


Annotations

Nullability annotations.

    <dependency>

      <groupId>com.github.spotbugs</groupId>

      <artifactId>spotbugs-annotations</artifactId>

      <version>4.7.2</version>

      <scope>provided</scope>

    </dependency>

Previously was implemented in dependency com.google.code.findbugs:annotations:3.0.1


Nullable like (annotations)

PROs: n/a

CONs: Unrecognized by Sonar v8.9.7


PROs: n/a

CONs: Former, non-jakarta


PROs: Spring Boot annotation

CONs: n/a


NotNull like (annotations)

PROs: Recognized by lombok @RequiredArgsConstructor

CONs: n/a


PROs: JSR 305, Recognized by lombok @RequiredArgsConstructor

CONs: Former, non-jakarta. Unrecognized by springdoc-openapi (instead use org.springframework.lang.NonNull)


PROs: JSR 303. Recognized by Spring Boot. Recognized by springdoc-openapi. Supported in generic type arguments (Set<@NonNull Mytype>)

CONs: Unrecognized by lombok @RequiredArgsConstructor (either use modifier 'final' or  add @lombok.NonNull or add @jakarta.annotation.Nonnull)


PROs: JSR 303. Recognized by Spring Boot. Recognized by springdoc-openapi. Supported in generic type arguments (Set<@NonNull Mytype>)

CONs: Unrecognized by lombok @RequiredArgsConstructor (either use modifier 'final' or  add @lombok.NonNull or add @jakarta.annotation.Nonnull)


PROs: Supported in generic type arguments (Set<@NonNull Mytype>)

CONs: n/a


PROs: JSR 305, Recognized by lombok @RequiredArgsConstructor & springdoc-openapi

CONs: Unsupported in generic type arguments (Set<@NonNull Mytype>)


Configuration

package-info.java

/**

 * <pre>

 * (at)NonNullApi should be used at package level in association with

 * org.springframework.lang.Nullable annotations at parameter and return value level.

 *

 * (at)NonNullFields should be used at package level in association with

 * org.springframework.lang.Nullable annotations at field level.

 * </pre>

 */

@NonNullApi

@NonNullFields

package edu.cou.myapp;


import org.springframework.lang.NonNullApi;

import org.springframework.lang.NonNullFields;