Skip to content

How to reuse @Schema annotation for dto fields #3085

@msaiducar

Description

@msaiducar

Is it somehow possible to reuse @Schema annotation?

In my project, to reduce the code duplication for @Parameter , I've created a custom annotation like below.

@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Parameter(
    description = "",
    example = "42424242-e89b-12d3-a456-426614174000",
    required = true,
    schema = @Schema(format = "uuid"))
public @interface UniqueIdFormat {

  @AliasFor(annotation = Parameter.class, attribute = "description")
  String description() default "Unique identifier of the entity";
}

Then, wherever I have id in the API (path parameter for example), I just annotate the arg with @UniqueIdFormat.

@GetMapping("/{id}")
@Operation(
    summary = "Get Customer",
    description = "Get customer information by their unique identifier")
public ResponseEntity<CustomerResponse> getCustomer(
   @UniqueIdFormat(description` = "Customer ID") @PathVariable UUID id) {
  Customer customer = customerService
          .findCustomerById(id)
          .orElseThrow(() -> new IllegalArgumentException("Customer not found: " + id));
  return ResponseEntity.ok(new CustomerResponse(customer));
}

Swagger looks like below.

Image

I wonder if I can do the same for @Schema ?

Below doesn't work.

@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Schema(description = "Customer's first name", example = "Sherlock", minLength = 1, maxLength = 50)
public @interface CustomerFirstName {}
@Schema(description = "Customer information response")
public class CustomerResponse {

  @UniqueIdFormat(description = "Customer ID")
  private UUID id;

  @CustomerFirstName private String firstName;

  @Schema(description = "Customer's last name", example = "Holmes")
  private String lastName;
}

As you can see below;

  • id field marked as uuid format but I think it is coming from UUID object type.
  • firstName doesnt have any constaints or example values
  • lastName has everything since @Schema used directly.
Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions