Skip to content

[REQ][spring] Null-Safety annotations #14427

Description

@frecco75

Is your feature request related to a problem? Please describe.

Manage null safety for object properties with Spring annotations (@NonNull, @Nullable).
Example: https://www.baeldung.com/spring-null-safety-annotations

Describe the solution you'd like

I'd like to add a config option useSpringNullSafety for the spring generator (false by default), to add Spring Null-Safety annotations (either @NonNull or@Nullable, depending of the nullable attribute of the OAS model).

Example:

Pet:
  properties:
    name:
       type: string
       example: 'scooby-doo'
       nullable: false
    breed:
        type: string
        example: 'German mastiff'
        nullable: true

should generate a model:

import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

@Generated(value = "org.openapitools.codegen.languages.SpringCodegen")
public class Pet {

  @JsonProperty("name")
  @NonNull
  private String name;

  @JsonProperty("breed")
  @Nullable
  private String breed = null;

  public Pet name(@NonNull String name) {
    this.name = name;
    return this;
  }

  /**
   * Get name
   * @return name
  */
  
  @Schema(name = "name", example = "scooby-doo", required = false)
  @NonNull
  public String getName() {
    return name;
  }

  public void setName(@NonNull String name) {
    this.name = name;
  }

  public Pet breed(@Nullable String breed) {
    this.breed = breed;
    return this;
  }

  /**
   * Get breed
   * @return breed
  */
  
  @Schema(name = "breed", example = "German mastiff", required = false)
  @Nullable
  public String getBreed() {
    return breed;
  }

  public void setBreed(@Nullable String breed) {
    this.breed = breed;
  }

 ....
}

Describe alternatives you've considered

Maybe it should be similar to the useOptional config option, so that it should be based on the required OpenAPI attribute.

Additional context

It is better for Kotlin interoparibilty. As it is mentionned in Kotlin reference, Java object are natively resolved as platform type.
With contextual annotations, the Kotlin compiler can provide null-safety type checking.

https://kotlinlang.org/docs/java-interop.html#null-safety-and-platform-types

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions