網頁

2019/9/2

Spring Boot 使用Springfox Swagger UI套件產生REST API文件
Use Springfox Swagger UI to generate REST API documents

本篇介紹如何在Spring Boot專案中利用Springfox的套件幫助產生REST API文件。


在專案的pom.xml加入SpringFox SwaggerSpringFox Swagger UI的依賴。

pom.xml

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

在Spring Boot專案新增以下@Configuration配置類。

package com.abc.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  
          .select()                                  
          .apis(RequestHandlerSelectors.any())              
          .paths(PathSelectors.any())                          
          .build();                                           
    }
}


完成以上設定後在本機開啟 http://localhost:8080/<appName>/swagger-ui.html 進入Swagger UI,
<appName>是應用程式contextPath名稱,例如http://localhost:8080/demo/swagger-ui.html

訪問Swagger UI頁面如果出現404 Not Found錯誤,則新增WebMvcConfigurer的類別來解決。

package com.abc.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

Swagger UI畫面如下。



此頁面實際上來自於springgox-swagger-ui.jar裡面的META-IFN/resources/webjars/META-IFN/resources/swagger-ui.html




參考:

沒有留言:

張貼留言