在 pom.xml
中添加 io.springfox:springfox-swagger2
和 io.springfox:springfox-swagger-ui
依赖
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency>
创建 Swagger2Config
配置类
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; @Configuration public class Swagger2Config { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("{Controler 扫描路径}")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("{标题}") .description("{描述}") .termsOfServiceUrl("{网址}") .version("{版本号}") .build(); } }
注意:
需要在 RequestHandlerSelectors.basePackage
参数中设置 Controller
包路径,否则生成的文档扫描不到接口
在 Application
中添加 @EnableSwagger2
注解
@EnableSwagger2 @SpringBootApplication public class ServiceAdminApplication { public static void main(String[] args) { SpringApplication.run(ServiceAdminApplication.class, args); } }
在 Controller
中的请求接口里加入以下常用 Swagger
注解
@RestController @RequestMapping(value = "/api/v2/user") @Api(tags = "用户管理") public class UserController() { @ApiOperation(value = "分页查询用户列表") @ApiImplicitParams({ @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "int", paramType = "path"), @ApiImplicitParam(name = "pageSize", value = "页数", required = true, dataType = "int", paramType = "path"), @ApiImplicitParam(name = "UserJson", value = "对象 JSON 字符串", required = false, dataTypeClass = String.class, paramType = "json") }) @RequestMapping(value = "page/{pageNum}/{pageSize}", method = RequestMethod.GET) public BaseResult page( @PathVariable(required = true) int pageNum, @PathVariable(required = true) int pageSize, @RequestParam(required = false) String UserJson ){ return null; } }
Controller HTTP HTTP API
启动项目,访问 Swagger
地址: http://
{ip}:{port}/swagger-ui.html