iT邦幫忙

0

[Springfox]使用筆記-01

  • 分享至 

  • xImage
  •  

SpringFox設定

maven dependency

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

如何讀取Docket

springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper為起點
https://ithelp.ithome.com.tw/upload/images/20220310/201458562cWnN2TJRg.png

因實作SmartLifecycle會等所有的Bean準備完成,並執行實作方法start()
https://ithelp.ithome.com.tw/upload/images/20220310/20145856jI606Vr5h0.png

開始掃描Docket建立Documentation最後放入DocumentationCache
https://ithelp.ithome.com.tw/upload/images/20220310/20145856NDjB1rWRx9.png

當呼叫path/v3/api-docs,就會回傳swagger的json文件,OpenApiControllerWebMvc是預設的API Controller
https://ithelp.ithome.com.tw/upload/images/20220310/20145856v7acT7CbMY.png

DocumentationCache取出Documentation處理完成後並回傳,就是我們看到的json檔案
https://ithelp.ithome.com.tw/upload/images/20220310/20145856QgmzQok9No.png

Docket建立

範例程式

@Bean
Docket docket() {
    return new Docket(DocumentationType.OAS_30)
                .servers(new Server("test", "http://localhost", "test",
                    Collections.EMPTY_LIST, Collections.EMPTY_LIST)) // 目前有些問題
                .groupName("API文件")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.app"))
                .paths(PathSelectors.regex("/api/hello/.*"))
                .build();
}

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
        .title("測試api")
        .description("測試用的的api")
        .contact(new Contact("Lucas", "聯絡的網址", "聯絡的mail"))
        .version("1.0.0") // api的版本
        .build();
}

Docket裡的servers沒有反應 issue
目前Docket裡的servers是被放到Documentation的resourceListing而非Documentation的servers,所以在controller取出Documentation放入OpenAPI的servers就沒有改變
https://ithelp.ithome.com.tw/upload/images/20220310/20145856DQuVwMDDio.png
https://ithelp.ithome.com.tw/upload/images/20220310/20145856usArA5kSZN.png

暫時解決方式

建立一實作WebMvcOpenApiTransformationFilter的Bean

@Override
public OpenAPI transform(OpenApiTransformationContext<HttpServletRequest> context) {
    OpenAPI openApi = context.getSpecification();
    Server server = new Server();
    server.setDescription("test");
    server.setUrl("http://localhost");
    List<Server> servers = new ArrayList<>(openApi.getServers());
    servers.add(server);
    openApi.setServers(servers);
    return openApi;
}

@Override
public boolean supports(DocumentationType documentationType) {
    return documentationType.equals(DocumentationType.OAS_30);
}

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言