如何配置swgger以及使用方法(postman,apipost)
一.如何配置swgger
1.引入依赖:我配置的是swgger2,如果需要其他版本,可以自行百度
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.4.0</version> </dependency>
2.配置config(配置文件)
package com.example.springbootdemo.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.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class Swagger2 { //swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等 @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //为当前包路径 .apis(RequestHandlerSelectors.basePackage("com.example.springbootdemo"))//这里是你springboot启动器的路径相对路径 .paths(PathSelectors.any()) .build(); } //构建 api文档的详细信息函数,注意这里的注解引用的是哪个 private ApiInfo apiInfo() { return new ApiInfoBuilder() //页面标题 .title("Spring Boot 测试使用 Swagger2 构建RESTful API") //创建人 .contact(new Contact("xiaoLiang", "http://www.baidu.com", "")) //版本号 .version("1.0") //描述 .description("API 描述") .build(); } }
3.编写一个controller测试一下
package com.example.springbootdemo.controller; import com.example.springbootdemo.entity.User; import org.springframework.web.bind.annotation.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @RestController @RequestMapping("/user") @Api(value = "/user") public class SwagController { @ApiOperation(value = "查询用户", notes = "查询用户") @PostMapping(value = "/getName") @ResponseBody public User getName(@RequestBody User userName) { System.out.println(userName.toString()); return userName; } }
4.我没有配置端口号默认就是localhost:8080/doc.html访问swgger2
5.postman是一样的