作者:翟永超;

來源:公衆號程序猿DD

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

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

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

我們可以通過源碼的註釋瞭解到一切:


public @interface ApiModelProperty {
/**
* Limits the acceptable values for this parameter.
*


* There are three ways to describe the allowable values:
*


    *
  1. To set a list of values, provide a comma-separated list.
    * For example: {@code first, second, third}.

  2. *
  3. 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)}.

  4. *
  5. 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.

  6. *

*/
String allowableValues() default "";
...
}


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


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


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


Swagger中配置了ApiModelProperty的allowableValues屬性問題


相關文章