修改springfox-swagger源碼,使example中時間格式默認爲「yyyy-MM-dd HH:mm:ss」

修改swagger源碼,使example中時間格式默認爲「yyyy-MM-dd HH:mm:ss」

前言

簡單點說,在swagger中,怎麼能針對如下vo中的java.util.Date類型的字段:createDate,html

能在swagger的界面上達到下面的效果呢?java

若是嘗試過的同窗,可能知道,這裏,若是不作任何修改的話,出來的效果是下面這樣的:spring

解決方法

我一開始百度搜了下,找到了這篇:數據庫

http://www.javashuo.com/article/p-ohoecudl-ek.htmlmaven

它的解決辦法呢,是在ApiModelProperty註解上加了 example 屬性,即下圖所示:ui

/**
     * 建立時間
     */
    @ApiModelProperty(value = "建立時間", example = "2019-10-30 15:34:12")
    private Date createDate;

我吧,感受這樣也很麻煩,若是可以感知到是Date類型,自動就把 example設爲上述格式多好?this

不用多說,估計要改源碼了。code

個人辦法是,從 example()方法入手,查找使用到它的地方(記得maven要勾選下載源碼),咱們發現了以下兩處:xml

斷點打在上面的方法內以後,再次運行,尋找合適的切入點,發現其調用堆棧以下:htm

最終修改方法以下:

在工程裏,新建了一個同包名同類名的 springfox.documentation.builders.ModelPropertyBuilder類,而後修改以下方法:

這裏,簡單附上代碼,修改得不多:

## springfox.documentation.builders.ModelPropertyBuilder    
    /**
     * Updates the example
     * @param example - example value
     * @return this
     * @deprecated @since 2.8.1 Use the one with Object as parameter
     */
    @Deprecated
    public ModelPropertyBuilder example(String example) {
        if ("java.util.Date" .equals(qualifiedType)) {
            this.example = "2019-10-30 15:34:12";
        }else {
            this.example = defaultIfAbsent(example, this.example);
        }
        return this;
    }

具體的swagger版本可能有微小差異,但差異應該不大,我這邊是最新版的2.9.2

<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>

總結

總體來講,只是覆蓋jar包的類,很簡單,主要是理清其邏輯。若是不清楚怎麼覆蓋jar包的類,可參考我上一篇文章。

懶要懶到底,能自動的就不要手動,Hibernate正向工程完成Oracle數據庫到MySql數據庫轉換(含字段轉換、註釋)

相關文章
相關標籤/搜索