1.pom.xml中引入依賴
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency>
方式一:Application.java中引入 @EnableSwagger2來啟動swagger注解
@SpringBootApplication // 組件掃描 @EnableSwagger2 public class Application { }
方式二:創建Swagger2配置類
package com.fz.hr.config; import io.swagger.annotations.ApiOperation; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 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.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration @EnableSwagger2 @ConditionalOnProperty(prefix = "hr", name = "swagger-open", havingValue = "true") public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) //這里采用包含注解的方式來確定要顯示的接口 //.apis(RequestHandlerSelectors.basePackage("com.fz.hr.modules.system.controller")) //這里采用包掃描的方式來確定要顯示的接口 .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("HR Doc") .description("HR Api文檔") .contact("WH") .version("2.0") .build(); } }
如上代碼所示,通過@Configuration
注解,讓Spring來加載該類配置。
再通過@EnableSwagger2
注解來啟用Swagger2。
再通過createRestApi
函數創建Docket
的Bean之后,apiInfo()
用來創建該Api的基本信息(這些基本信息會展現在文檔頁面中)。
select()
函數返回一個ApiSelectorBuilder
實例用來控制哪些接口暴露給Swagger來展現,本例采用指定掃描的包路徑來定義,
Swagger會掃描該包下所有Controller定義的API,並產生文檔內容(除了被@ApiIgnore
指定的請求)
接口注解
@RestController
@RequestMapping("/user") @Api("userController相關api") public class UserController { @Autowired private UserService userService; @ApiOperation("獲取用戶信息") @ApiImplicitParams({ @ApiImplicitParam(paramType="header",name="username",dataType="String",required=true,value="用戶的姓名",defaultValue="zhaojigang"), @ApiImplicitParam(paramType="query",name="password",dataType="String",required=true,value="用戶的密碼",defaultValue="wangna") }) @ApiResponses({ @ApiResponse(code=400,message="請求參數沒填好"), @ApiResponse(code=404,message="請求路徑沒有或頁面跳轉路徑不對") }) @RequestMapping(value="/getUser",method=RequestMethod.GET) public User getUser(@RequestHeader("username") String username, @RequestParam("password") String password) { return userService.getUser(username,password); } }
訪問地址:訪問:http://localhost:8080/swagger-ui.html
參考:
https://swagger.io/