'How to use a method to dinamically return the desired value for swagger documentation

Currently we have enum descriptions hardcoded on ApiModelProperty. This sucks, because we need to remember to update it everytime we change the enum. It would be great to be able to get this dinamically.

There is a way to get the example code below working? I mean anything which reaches the same goal.

public enum Color {
    BLUE("B", "Blue is so cool"),
    RED("R", "It usually prepresents a negative amout"),
    ORANGE("O", "The fruit");

    private String code;
    private String description;

    private Color(String code, String description) {
        this.code = code;
        this.description = description;
    }

    public String getCode() {
        return this.code;
    }

    public String getDescription() {
        return this.description;
    }

    public static String getSwaggerValue() {
        StringBuilder sb = new StringBuilder();

        for (Color color : Color.values()) {
            sb.append("<br/>").append(color.getCode()).append(" - ").append(color.getDescription());
        }

        return sb.toString();
    }
}

public class MyTestClass {

    @ApiModelProperty(value = Color.getSwaggerValue())
    private String myString;
    ...
}

Simplified pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.5</version>
    <relativePath />
</parent>

<dependencies>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

I'm using java 11.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source