1.首先在pom中项目中导入Swagger的依赖:(需要两个依赖,一个springfox-swagger2,一个springfox-swagger-ui)
<!--swagger--> <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.导入依赖后,再写一个Swagger配置类开启Swagger:(配置类中什么都不写就是默认的,也可以自定义配置)
@Configuration @EnableSwagger2 public class SwaggerConfig { }
@Configuration表明这是一个注解类,@EnableSwagger2表示开启Swagger2。也可以在启动类上加上@EnableSwagger2开启注解。
3.在浏览器输入网址到Swagger页面:http://localhost:8080/swagger-ui.html ,如果控制层注入容器即添加有@RestController。就自动可以识别接口并显示到文档中。
补充:自定义文档信息
@Configuration public class SwaggerConfig { /** * 创建API应用 * apiInfo() 增加API相关信息 * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现, * 本例采用指定扫描的包路径来定义指定要建立API的目录。 * */ @Bean public Docket creatRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.ape.hospital_order.controller")) .paths(PathSelectors.any()) //定义哪些路径的接口需要生成文档 .build(); } /** * 创建该API的基本信息(这些基本信息会展现在文档页面中) * 访问地址:http://项目实际地址/swagger-ui.html */ private ApiInfo apiInfo(){ Contact contact = new Contact("用户名", "www.yonghu.cn", "12345678@qq.com"); return new ApiInfoBuilder() .title("xxx系统") //文档首页标题 .version("1.0") // 文档版本 .description("xxx系统描述") .contact(contact) // 创建者信息 .build(); } }
4.在类或方法上添加注解,对类和接口说明:
@RestController @RequestMapping("/checkitem") @Api(tags = "业务的说明",value = "/路径") public class CheckItemController { @PostMapping("/find") @ApiOperation(value = "查找页面", notes = "分页查询") public One find(@RequestBody Query query){ /****/ return One; } //检查项的添加 @PostMapping("/save") @ApiOperation(value = "项目的添加", notes = "添加") public Two save(@RequestBody Add add){ /****/ return Two; } }