Swagger中配置了@ApiModelProperty的allowableValues屬性但不顯示的問題


現在用Swagger來生成API文檔的例子已經非常多了,今天碰到開發同事問了一個問題,幫着看了一下,主要還是配置方法的問題,所以記錄一下。如果您也碰到了同樣的問題,希望本文對您有用。

問題描述

@ApiModelProperty注解是用來給屬性標注說明、默認值、是否可以為空等配置使用的,其中有一個屬性allowableValues是本文要講的重點,從屬性命名上就能知道,該屬性用來配置所標注字段允許的可選值。

但是這個屬性是一個String類型,我們要如何配置可選值呢?

我們可以通過源碼的注釋了解到一切:

public @interface 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 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 range[1, 5]}, {@code 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 "";

    ...
}

我們只需要通過,分割來定義可選值,或者用range函數定義范圍等方式就能正確顯示了,比如:

public class Filter {

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

}

再運行下程序,就能看到如下內容,設置的允許值正常顯示了。
pasted-123.png


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM