I'm looking a way to simplify code when using annotations as a DSL

Situation
We are designing a new REST API and using swagger annotations to document our Spring controller methods. I discovered that many “constructions” are boilerplate and repeatedly appear.
Example:

    @Operation(
        summary = "...",
        description = "...",
        responses = [
            ApiResponse(
                responseCode = "200",
                description = "Ok",
            ),
            ApiResponse(
                responseCode = "204",
                description = "No contet",
                content = [Content(schema = Schema(implementation = Void::class))]
            ),
            ApiResponse(
                responseCode = "201",
                headers = [
                    Header(
                        name = "Location",
                        description = "The location of the created resource",
                        schema = Schema(implementation = Void::class)
                    )
                ],
                description = "...",
            ),
        ]
    )

I want to extract some “standard construction” and reuse them.
I can not create “const val” from annotation because it is not a primitive type. Inline functions are not acceptable as well.

Any propositions?

1 Like

The way I’ve got around that issue in my Dropwizard project is just to define my own annotations and annotate them with the Swagger annotations.

@ApiResponse(
    responseCode = "403",
    description = "You are not allowed to perform the requested action.",
    content = [
        Content(
            mediaType = MediaType.APPLICATION_JSON,
            schema = Schema(implementation = ErrorResponse::class)
        )
    ]
)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class Forbidden

@ApiResponse(
    responseCode = "500",
    description = "Something went wrong when processing the request.",
    content = [
        Content(
            mediaType = MediaType.APPLICATION_JSON,
            schema = Schema(implementation = ErrorResponse::class)
        )
    ]
)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class ServerErrorResponse

class MyRestResource {
    @Forbidden
    @ServerErrorResponse
    fun myResource() {}
}
1 Like

Thank you
It could help