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


修改swagger源碼,使example中時間格式默認為“yyyy-MM-dd HH:mm:ss”

前言

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

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

如果嘗試過的同學,可能知道,這里,如果不做任何修改的話,出來的效果是下面這樣的:

解決方法

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

https://www.cnblogs.com/yanfeiLiu/p/9792042.html

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


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

我吧,感覺這樣也很麻煩,如果能夠感知到是Date類型,自動就把 example設為上述格式多好?

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

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

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

最終修改方法如下:

在工程里,新建了一個同包名同類名的 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數據庫轉換(含字段轉換、注釋)


免責聲明!

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



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