SpringBoot + Swagger + swagger-bootstrap-ui製作在線API文檔

SpringBoot + Swagger + swagger-bootstrap-ui製作在線API文檔

Swagger這個框架我想大部分人多多少少有聽說或者接觸過,這個框架的宗旨在於簡化後臺開發者寫doc api接口時間,在開發過程中,只要加入一些註解以及註釋,就能被編譯成一個網頁,訪問網頁後的在線接口文檔,都是配置好的,並且有個按鈕,可以提供前端調試接口,查看返回數據。

可以說這個框架挺好的,入參的參數,參數類型,是否非空,請求頭等等;不足的地方在於Swagger提供的Swagger-UI樣式是真的不好看。。。這個是值得吐槽的地方。

也是因爲一個東西的不足,自然會有人去完善,swagger-bootstrap-ui的出現就是爲了彌補這個樣式的不足,與原生Swagger-UI毫無衝突;這個框架主要優化了原生框架頁面樣式的排版,加入了bootstrap樣式元素,看着更舒服。

1. 引入pom文件

		<!--Swagger相關jar-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!--bootstrap-ui-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.8.7</version>
        </dependency>

頭兩個引入Swagger框架沒問題,重要的是引入最後的UI框架,這個要和Swagger一起

2. 加入配置類

import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Swagger配置類
 * @author 如漩渦
 */
@Configuration
@EnableSwagger2
public class Swagger {
    /**
     * apis這個方法說明一下,這個方法主要是掃描帶有註解“@Api”的類
     */
    @Bean
    public Docket creatRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * API訪問路徑:/doc.html
     * title: 模塊名稱
     * contact:創建人信息
     * description: 模塊描述
     * version:版本
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("後臺API接口文檔")
                .contact(new Contact("如漩渦", "xx", "**"))
                .description("後臺端")
                .version("0.0.1")
                .build();
    }
}

最好把這個類與啓動類同級

創建Docket對象時,apis這個方法比較重要,是制定要生成接口文檔在哪個位置,有兩個方法,一個是RequestHandlerSelectors.withClassAnnotation,以上代碼塊中的這個方法,這個方法意思是掃描帶有@Api這個註解的類生成文檔,還有一個方法是RequestHandlerSelectors.basePackage,這個需要就需要制定目錄了,內置傳參是String類型,例如com.xx.xx.web,這個包地址是放置controller的,制定掃描。

另外還有一個配置類,是控制整個web配置的類,需要繼承WebMvcConfigurerAdapter

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

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
    /**
     * 資源映射
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

    /**
     * 添加攔截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(apiInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**")
                .excludePathPatterns("/error");
    }
    /**
     * 注入攔截器(自定義)
     * @return
     */
    @Bean
    public ApiInterceptor apiInterceptor(){
        return new ApiInterceptor();
    }

}

重要的代碼塊在於addResourceHandlers這個重載的方法,在這個方法裏的內容是將Swagger-UI的網頁地址映射出去,避免被資源攔截。

另外如果項目中添加了攔截器的話,需要在攔截器排除掉Swagger-UI的請求,不然無法訪問到,代碼塊在addInterceptors這個方法中。

3. 註解的使用

在這裏我隨便拿出一個controller類來做示範

**
 * 項目管理controller
 *
 * @author 如漩渦
 */
@RestController
@RequestMapping("/project")
@Api(tags = {"項目管理"}, description = "相關接口")
public class OaProjectController{
    @Autowired
    private OaProjectService projectService;
    
    @ApiOperation(value = "表單列表", notes = "查詢")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "projectType", value = "項目類型(1:上線;2:未上線)", required = false, dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "projectStatus", value = "項目狀態(1:進行中;2:暫停;3:已完結/廢棄)", required = false, dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "departmentId", value = "出品方ID", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "name", value = "項目名稱", required = false, dataType = "String")
    })
    @GetMapping("/list")
    public Result list(@RequestParam(required = false) Integer projectType,
                       @RequestParam(required = false) Integer projectStatus,
                       @RequestParam(required = false) String departmentId,
                       @RequestParam(required = false) String name){
        
        List<OaProjectDTO> list = projectService.list(projectType, projectStatus, departmentId, name);
        
        return ResultUtil.success(list);
    }
}

@Api:這個註解在前面說過了,一方面用於配置類掃描,另一方面爲生成後的文檔產生標題;

@ApiOperation:註釋在方法上,爲方法生成備註作用;

@ApiImplicitParams:參數的註解,內置還需要ApiImplicitParam一起使用,兩個是一個組合;

還有一些其他註解,可以參考官網

4. 訪問網頁

準備工作都做好以後,項目啓動,訪問IP:端口號/doc.html即可

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章