新建SpringBoot项目,添加依赖
<!-- Swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </dependency>
项目主要文件结构
$ tree pom.xml src/main/java/com/example/demo ├── Application.java ├── config │ └── SwaggerConfig.java └── controller └── EmployeeController.java
配置类
package com.example.demo.config; 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 public class SwaggerConfig { @Bean public Docket docket() { // 扫描指定接口所在路径 return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build(); } // swagger 信息 public ApiInfo apiInfo() { return new ApiInfoBuilder() .title("利用swagger2构建的API文档") .description("用restful风格写接口") .termsOfServiceUrl("https://www.baidu.com/") .version("1.0") .build(); } }
控制器
package com.example.demo.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController @Api(value = "用户管理类", description = "接口描述") public class EmployeeController { @ApiOperation(value = "新增一个用户", notes = "新增一个用户") @GetMapping(value = "insert") public String insert(Map<String, Object> map) { return "hi"; } @ApiOperation(value = "更新一个用户", notes = "更新一个用户") @GetMapping(value = "update") public String update(Map<String, Object> map) { return "hi"; } }
文档页面:http://localhost:8080/swagger-ui.html
感觉入侵性太强了,而且配置参数较多,密密麻麻的
参考