Swagger是一個開源的接口配置文檔,通常用於先後端分離,代替後端人員爲前端人員書寫繁瑣的接口文檔,使後端人員從繁瑣的接口文檔中解脫出來。Swagger如何使用呢?首先咱們要在springboot中的pom文件引入依賴包html
<!-- swagger依賴組件 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
其次,添加swagger的配置文件,該配置文件定義了網頁訪問swagger2的路徑以及標題,描述等信息前端
package com.xash.quartzDemo.config; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configurable public class SwaggerConfig{ @Bean public Docket api(){ return new Docket(DocumentationType.SWAGGER_2) .groupName("測試模塊") .apiInfo(getApiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.xash.quartzDemo.controller")) .paths(PathSelectors.regex(".*/.*")) .build(); } private ApiInfo getApiInfo(){ return new ApiInfoBuilder() .title("測試模塊") .description("小標題") .version("1.0") .build(); } @Bean public Docket api1(){ return new Docket(DocumentationType.SWAGGER_2) .groupName("測試模塊1") .apiInfo(getApiInfo1()) .select() .apis(RequestHandlerSelectors.basePackage("com.xash.quartzDemo.controller")) .paths(PathSelectors.regex(".*/.*")) .build(); } @Bean private ApiInfo getApiInfo1(){ return new ApiInfoBuilder() .title("測試模塊1") .description("小標題") .version("1.0") .build(); } }
這樣,咱們就能夠在要添加接口文檔的地方利用註解添加相應的接口文檔信息了web
例如:spring
@Api(tags="這是個測試Controller")
public class PermissionController {}類上加註解,說明該類具備的功能後端
@ApiOperation(value = "根據用戶id查詢權限")
public String selectPermissionById(ModelMap map,@ApiParam("id") @RequestParam("id")int id){
System.out.println("開始查詢");
map.put("name", "歡飲使用thymeleaf模板引擎");
map.put("sysPermission", permissionService.selectPermissionById(id));
return "index";
}方法上加註解,表示方法的功能,以及可見在形參上加註解,指定形參,對形參進行描述api
訪問地址默認爲192.168.2.199:8080/項目應用/swagger2-ui.htmlspringboot