1. 程式人生 > >swagger暴露程序接口文檔

swagger暴露程序接口文檔

sel string 角色 tle new name run long 官方

Swagger2是一個幫助用戶、團隊、企業快速、高效、準確地生產API服務的工具組件,同時還提供了部分測試功能,它的官方網站是https://swagger.io/。

1.引入Maven

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

2.在應用啟動類上添加註解@EnableSwagger2用以開啟Swagger2

@SpringBootApplication
@EnableSwagger2
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

實際上在執行完上面兩個步驟後,接口就已經被暴露出來了,這時我們啟動應用,進入網站http://ip:port/swagger-ui.html,可以看到如下界面

技術分享圖片

上圖中已經暴露出來了四個不同的處理器,但是其中只有“user-controller”是由我們創建的,同時這些處理器和頁面中沒有任何的相關提示,讓人難以理解每個接口分別對應的功能。下面我們再進行第三步,對暴露出來的接口再進行詳細地描述。

3.添加API文檔描述

定義文檔的整體描述,和API文檔的規範

@Configuration
public class SwaggerConf {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())  
//Api信息 .select() //選擇器 .apis(RequestHandlerSelectors.basePackage("com.springboot.demo.controller")) //只有在這個包和子包下的接口被生成API文檔 .paths(PathSelectors.any()) //允許的路徑,可以指定post .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("swagger2 demo") //文檔標題 .description("swagger2的測試用例") //文檔說明 .contact(new Contact("yxf", "http://yxf.com", "[email protected]")) //文檔提供者的聯系方式 .version("1.0") //版本號 .build(); } }

再根據每個接口定義各自的相關描述

    /**
     *  [email protected] 描述Api的操作,包括請求名(value)和請求描述(notes)
     *  [email protected] 多個請求參數,裏面以數組形式存儲了單個的請求參數
     *  [email protected] 單個請求參數,name參數名,value參數描述,required必要性(針對部分參數可以為空的情況),
     *          example樣例格式(默認是“String”,0,true等)
     * @param id
     * @return
     */
    @ApiOperation(value = "刪除角色", notes = "根據ID刪除角色。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色ID", required = true, example = "1")
    })
    @DeleteMapping(value = "role/")
    public String removeRole(long id) {
        System.out.println("刪除角色");
        return "刪除成功" + id;
    }

如上編寫後,重啟應用再進入上面的方法路徑“/role/”查看:

技術分享圖片

點擊“try it out”

技術分享圖片

執行後下方會出現操作的相關信息:

技術分享圖片

swagger暴露程序接口文檔