SpringBoot2 整合 Swagger2文件 使用BootstrapUI頁面

趙小胖0914發表於2020-07-31

SpringBoot2 整合 Swagger2

SpringBoot整合三板斧

第一步、引入pom

<dependency>
  <groupId>com.spring4all</groupId>
  <artifactId>swagger-spring-boot-starter</artifactId>
  <version>1.9.0.RELEASE</version>
</dependency>
<dependency>
  <groupId>com.github.xiaoymin</groupId>
  <artifactId>swagger-bootstrap-ui</artifactId>
  <version>1.9.6</version>
</dependency>

<dependency>
  <groupId>io.swagger</groupId>
  <artifactId>swagger-annotations</artifactId>
  <version>1.5.22</version>
</dependency>
<dependency>
  <groupId>io.swagger</groupId>
  <artifactId>swagger-models</artifactId>
  <version>1.5.22</version>
</dependency>

swagger-spring-boot-starter該專案主要利用Spring Boot的自動化配置特性來實現快速的將swagger2引入spring boot應用來生成API文件,簡化原生使用swagger2的整合程式碼。

swagger-bootstrap-uispringfox-swagger的增強UI實現,為Java開發者在使用Swagger的時候,能擁有一份簡潔、強大的介面文件體驗

swagger-annotations,swagger-models是因為springfox-swagger2包裡有swagger-models-1.5.20.jar報錯。所以替換成1.5.22版本

java.lang.NumberFormatException: For input string: ""
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Long.parseLong(Long.java:601)
	at java.lang.Long.valueOf(Long.java:803)
	at io.swagger.models.parameters.AbstractSerializableParameter.getExample(AbstractSerializableParameter.java:412)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at......

看下1.5.20版本里AbstractSerializableParameter.java原始碼:

public Object getExample() {
    if (this.example == null) {
        return null;
    } else {
        try {
            if ("integer".equals(this.type)) {
                return Long.valueOf(this.example);
            }
        
            if ("number".equals(this.type)) {
                return Double.valueOf(this.example);
            }

            if ("boolean".equals(this.type) && ("true".equalsIgnoreCase(this.example) || "false".equalsIgnoreCase(this.defaultValue))) {
                return Boolean.valueOf(this.example);
            }
        } catch (NumberFormatException var2) {
            LOGGER.warn(String.format("Illegal DefaultValue %s for parameter type %s", this.defaultValue, this.type), var2);
        }

        return this.example;
    }
}

這裡只判斷了this.example == null才返回null,其餘會去進行轉換,而空字串也會進行轉換,導致格式丟擲格式化轉換異常.再來看下1.5.22版本里AbstractSerializableParameter.java原始碼:

public Object getExample() {
    if (this.example != null && !this.example.isEmpty()) {
        try {
            if ("integer".equals(this.type)) {
                return Long.valueOf(this.example);
            }

            if ("number".equals(this.type)) {
                return Double.valueOf(this.example);
            }

            if ("boolean".equals(this.type) && ("true".equalsIgnoreCase(this.example) || "false".equalsIgnoreCase(this.defaultValue))) {
                return Boolean.valueOf(this.example);
            }
        } catch (NumberFormatException var2) {
            LOGGER.warn(String.format("Illegal DefaultValue %s for parameter type %s", this.defaultValue, this.type), var2);
        }

        return this.example;
    } else {
        return this.example;
    } 
}

對example同時進行了null和空值的判斷,官方也發現了自己的這個問題,我們進行相應的替換即可

第二部、配置

swagger-spring-boot-starter相關配置資訊可參考如下地址:

swagger-bootstrap-ui相關配置資訊可參考如下地址:

官方地址:https://doc.xiaominfo.com/guide/

swagger-bootstrap-ui目前已改名了knife4j-spring-boot-starter

專案正式更名為knife4j,取名knife4j是希望她能像一把匕首一樣小巧,輕量,並且功能強悍,更名也是希望把她做成一個為Swagger介面文件服務的通用性解決方案,不僅僅只是專注於前端Ui前端.

swagger-bootstrap-ui的所有特性都會集中在knife4j-spring-ui包中,並且後續也會滿足開發者更多的個性化需求.

swagger:
  version: 1.0v # 版本號
  authorization: # 全域性引數
    name: Authorization # 鑑權策略ID,對應 SecurityReferences ID
    type: ApiKey # 鑑權策略,可選 ApiKey | BasicAuth | None,預設ApiKey
    key-name: X-Token # 鑑權傳遞的Header引數
  #    auth-regex: ^.*$ # 需要開啟鑑權URL的正則, 預設^.*$匹配所有URL
  ui-config: # 排序規則
    operations-sorter: method # 按方法定義順序排序
    tags-sorter: alpha # 按字母表排序
  docket: # 分組配置
    common:
      base-package: com.xxxx.a
      description: API介面文件
      title: xxx介面
      contact:
        name: xxx
        url: https://cn.bing.com/
    hq:
      base-package: com.xxxx.b
      description: API介面文件
      title: xxx介面
      contact:
        name: xxx
        url: https://zc.happyloves.cn:4443/wordpress/
    shop:
      base-package: com.xxxx.c
      description: API介面文件
      title: xxx介面
      contact:
        name: xxx
        url: https://zc.happyloves.cn

第三步、註解

@EnableSwagger2Doc // 啟用Swagger2
@EnableSwaggerBootstrapUI //啟用swagger-bootstrap-ui
@SpringBootApplication
public class WebApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }
}

編寫程式碼

@Api(value = "DemoOne-DemoOne服務~~~~~~~~", tags = {"1-DemoOne-DemoOne服務"})
@Slf4j
@Validated
@RestController
@RequestMapping("/common/DemoOne")
public class DemoOneController {
    private final DemoOneService service;

    @Autowired
    public DemoOneController(DemoOneService service) {
        this.service = service;
    }

    //=====================================================================================DELETE=====================================================================================
    @ApiOperation(value = "根據主鍵ID刪除", notes = "根據主鍵ID刪除~~~~~~~~~~~~~")
    @DeleteMapping("/{id}")
    public ApiMessage deleteById(@PathVariable @Min(1) int id) throws Exception {
        return service.deleteById(id);
    }

    //=====================================================================================GET========================================================================================

    @ApiOperation(value = "獲取所有資料", notes = "獲取所有資料~~~~~~~~~~~~~")
    @GetMapping("/")
    public ApiMessage<List<DemoOneResponse>> getAllList() {
        return service.getAllList();
    }

    @ApiOperation(value = "根據主鍵ID獲取資料", notes = "根據主鍵ID獲取資料~~~~~~~~~~~~~")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", required = true, value = "主鍵ID", paramType = "path", dataType = "string"),
    })
    @GetMapping("/{id}/{name}")
    public ApiMessage<DemoOneResponse> getById(@PathVariable @Min(1) int id, @PathVariable @AssertFalse boolean name) {
        return service.getById(id);
    }

    //=====================================================================================POST=======================================================================================
    @ApiOperation(value = "新增DemoOne資料", notes = "新增DemoOne資料~~~~~~~~~~~~~")
    @PostMapping("/")
    public ApiMessage<DemoOneResponse> save(@RequestBody @Valid DemoOneRequest parameter) {
        return service.addDemoOne(parameter);
    }

    //=====================================================================================PUT========================================================================================
    @ApiOperation(value = "更新DemoOne資料", notes = "更新DemoOne資料~~~~~~~~~~~~~")
    @PutMapping("/")
    public ApiMessage<DemoOneResponse> update(@RequestBody @Valid DemoOneRequest parameter) {
        return service.update(parameter);
    }

大功告成!!!啟動訪問如下地址:

Swagger2地址:

http://${ip地址}?{埠}/swagger-ui.html

swagger-bootstrap-ui地址:

http://${ip地址}?{埠}/doc.html
趙小胖個人部落格:https://zc.happyloves.cn:4443/wordpress/

相關文章