Spring Boot 配置 Swagger(3.0.0 版本)
添加 Swagger 依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
创建 Swagger 配置类
package com.app.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.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.app.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("RESTful APIs")
.description("RESTful APIs")
.termsOfServiceUrl("http://localhost:8080/")
.contact(new Contact("jack", "www.baidu.com", "jack@qq.com"))
.version("1.0")
.build();
}
}
编写接口文档
package com.app.controller;
import java.util.logging.Logger;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
@Api(tags = "文章接口")
@RestController
@RequestMapping("/chapter")
public class ArticleController {
Logger logger = Logger.getLogger("com.app.controller.ChapterController");
@ApiOperation(value = "获取指定id的文章", notes = "根据URL的id获取指定文章的信息")
@ApiImplicitParam(name = "id", value = "文章id", required = true, dataType = "Long", dataTypeClass = Long.class)
@GetMapping("/{id}")
public String getOne(@PathVariable Long id) {
logger.info(id + "");
return id + "";
}
@ApiOperation(value = "删除指定id的文章", notes = "根据URL的id删除指定文章的信息")
@ApiImplicitParam(name = "id", value = "文章id", required = true, dataType = "Long", dataTypeClass = Long.class)
@DeleteMapping("/{id}")
public String deleteOne(@PathVariable Long id) {
logger.info(id + "");
return id + "";
}
}
注解说明:
- @Api:描述类/接口的主要用途。
- @ApiOperation:描述方法用途,给 API 增加说明。
- @ApiImplicitParam:描述方法的参数,给参数增加说明。
- @ApiImplicitParams:描述方法的参数(Multi-Params),给参数增加说明。
- @ApiIgnore:忽略某类/方法/参数的文档。
测试访问
通过访问以下链接进入 swagger 页面。