The allowableValues property of @ApiModelProperty is configured in Swagger, but the problem is not displayed

Keywords: Programming Attribute

Now there are many examples of using Swagger to generate API documents. Today, I met a question from my development colleague. For a look, the main problem is the configuration method, so record it. If you encounter the same problem, I hope this article is useful for you.

Problem description

The @ApiModelProperty annotation is used to annotate properties, default values, whether they can be used for empty configurations, and so on. One of the properties allowableValues is the focus of this article. It can be seen from the naming of attributes that this attribute is used to configure the optional values allowed by the annotated fields.

But this property is a String type. How do we configure the optional values?

We can learn everything from the source annotations:

public [@interface](https://my.oschina.net/u/996807) ApiModelProperty {

    /**
     * Limits the acceptable values for this parameter.
     * <p>
     * There are three ways to describe the allowable values:
     * <ol>
     * <li>To set a list of values, provide a comma-separated list.
     * For example: {[@code](https://my.oschina.net/codeo) first, second, third}.</li>
     * <li>To set a range of values, start the value with "range", and surrounding by square
     * brackets include the minimum and maximum values, or round brackets for exclusive minimum and maximum values.
     * For example: {[@code](https://my.oschina.net/codeo) range[1, 5]}, {[@code](https://my.oschina.net/codeo) range(1, 5)}, {@code range[1, 5)}.</li>
     * <li>To set a minimum/maximum value, use the same format for range but use "infinity"
     * or "-infinity" as the second value. For example, {@code range[1, infinity]} means the
     * minimum allowable value of this parameter is 1.</li>
     * </ol>
     */
    String allowableValues() default "";

    ...
}

We only need to define optional values by partitioning, or define ranges by range functions to display them correctly, for example:

public class Filter {

    @ApiModelProperty(allowableValues = "range[1,5]")
    Integer order
    @ApiModelProperty(allowableValues = "111, 222")
    String code;

}

Then run the program, you can see the following content, the allowable value set normal display.

Posted by timlondon on Mon, 28 Jan 2019 16:21:14 -0800