- 引入依赖。
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.5.0</version> </dependency> <!-- swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
- Swagger配置类
@Configuration @EnableSwagger2 public class Swagger2Config { //swagger2的配置文件 @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //配置Swagger2包扫描路径 .apis(RequestHandlerSelectors.basePackage("com.freesky")) .paths(PathSelectors.any()) .build(); } //构建API文档的信息函数 private ApiInfo apiInfo() { return new ApiInfoBuilder() //页面标题 .title("SpringBoot使用Swagger2的DEMO") //创建人 .contact(new Contact("Freesky", "https://blog.csdn.net/qwqw3333333/article/details/84606975", "569265915@qq.com")) //版本号 .version("1.0.0") //描述 .description("这个一个用SpringBoot和Swagger搭建的API") .build(); } }
- 测试Controller。
@RestController @RequestMapping("/api") @Api("SwaggerDemoController相关的api") public class SwaggerDemoController { private static final Logger logger= LoggerFactory.getLogger(SwaggerDemoController.class); /** * httpMethod 需要大写,"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH" * @param name * @return */ @ApiOperation(value = "对名为 name的人打招呼", httpMethod = "GET") @ApiImplicitParam(name = "name", value = "姓名", paramType = "PathVariable", required = true, dataType = "String") @GetMapping(value = "/{name}") public String hello(@PathVariable String name) { logger.info(String.format("开始对[%s]打招呼",name)); return String.format("你好,%s!",name); } }
- 启动,访问:http://localhost:8080/swagger-ui.html