Swagger中配置了@ApiModelProperty的allowableValues屬性但不顯示的問題
現(xiàn)在用Swagger來生成API文檔的例子已經(jīng)非常多了,今天碰到開發(fā)同事問了一個問題,幫著看了一下,主要還是配置方法的問題,所以記錄一下。如果您也碰到了同樣的問題,希望本文對您有用。
問題描述
@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函數(shù)定義范圍等方式就能正確顯示了,比如:
- public class Filter {
- @ApiModelProperty(allowableValues = "range[1,5]")
- Integer order
- @ApiModelProperty(allowableValues = "111, 222")
- String code;
- }
再運行下程序,就能看到如下內(nèi)容,設(shè)置的允許值正常顯示了。
【本文為51CTO專欄作者“翟永超”的原創(chuàng)稿件,轉(zhuǎn)載請通過51CTO聯(lián)系作者獲取授權(quán)】