SpringBoot集成Swagger
Swagger-UI
简介
Swagger-UI是HTML, Javascript, CSS的一个集合,可以动态地根据注解生成在线API文档。
常用注解
- @Api:用于修饰Controller类,生成Controller相关文档信息
- @ApiOperation:用于修饰Controller类中的方法,生成接口方法相关文档信息
- @ApiParam:用于修饰接口中的参数,生成接口参数相关文档信息
- @ApiModelProperty:用于修饰实体类的属性,当实体类是请求参数或返回结果时,直接生成相关文档信息
整合Swagger
添加项目依赖
SpringBoot版本选择的是2.6.x, 在pom.xml中新增Swagger依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
路径匹配处理
Springfox使用的路径匹配基于AntPathMatcher,而Spring Boot 2.6.x 使用的是PathPatternMatcher
方法一:启动类添加注解@EnableWebMvc
方法二:配置文件中添加mvc默认的路径匹配策略
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER
添加Swagger配置
注意:Swagger对生成API文档的范围有三种不同的选择
- 生成指定包下面的类的API文档
- 生成存在@Api注解的类的API文档
- 生成存在@ApiOperation指定注解的方法的API文档
package com.test.config;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
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.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(true)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.test.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SwaggerUI For borrow")
.description("cloud-borrow")
.contact(new Contact("XiaoYuanJW", "https://xiaoyuanjw.github.io/", "xxx@qq.com"))
.version("1.0")
.build();
}
@Bean
public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
return new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
}
return bean;
}
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
List<T> copy = mappings.stream()
.filter(mapping -> mapping.getPatternParser() == null)
.collect(Collectors.toList());
mappings.clear();
mappings.addAll(copy);
}
@SuppressWarnings("unchecked")
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
try {
Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
field.setAccessible(true);
return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
};
}
}
实体类添加Swagger注解
package com.test.entity;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Borrow {
@ApiModelProperty(value = "借阅id")
Long id;
@ApiModelProperty(value = "用户id")
Long uid;
@ApiModelProperty(value = "图书id")
Long bid;
}
Controller添加Swagger注解
package com.test.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSONObject;
import com.test.entity.*;
import com.test.service.BorrowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@Api(tags = "BorrowController", description = "借阅信息管理")
@RestController
@RequestMapping("/borrow")
@Slf4j
public class BorrowController {
@Resource
BorrowService borrowService;
@ApiOperation("根据用户id获取借阅信息")
@GetMapping(value = "/user/{uid}", produces = "application/json;charset=UTF-8")
public UserBorrowDetail getBorrowByUser(@PathVariable("uid") @ApiParam("用户id") Long uid){
return borrowService.getBorrowByUser(uid);
}
@ApiOperation("根据图书id获取借阅信息")
@GetMapping(value = "/book/{bid}", produces = "application/json;charset=UTF-8")
public BookBorrowDetail getBorrowByBook(@PathVariable("bid") @ApiParam("图书id") Long bid){
return borrowService.getBorrowByBook(bid);
}
@ApiOperation("根据用户id和图书id获取借阅信息")
@GetMapping(value = "/getborrow", produces = "application/json;charset=UTF-8")
public BorrowDetail getBorrow(@RequestParam(value = "uid", required = true) @ApiParam("用户id") Long uid,
@RequestParam(value = "bid", required = true) @ApiParam("图书id") Long bid){
return borrowService.getBorrow(uid, bid);
}
@ApiOperation("图书借阅")
@PostMapping(value = "/{uid}/{bid}", produces = "application/json;charset=UTF-8")
public JSONObject borrow(@PathVariable("uid") @ApiParam("用户id") Long uid,
@PathVariable("bid") @ApiParam("图书id") Long bid) {
boolean result = borrowService.borrow(uid, bid);
JSONObject jsonObject = new JSONObject();
if (result) {
jsonObject.put("code", 200);
jsonObject.put("success", true);
jsonObject.put("message", "借阅成功");
return jsonObject;
}
jsonObject.put("code", 100);
jsonObject.put("success", false);
jsonObject.put("message", "借阅失败");
return jsonObject;
}
}
运行测试
运行服务并访问:http://localhost:8301/swagger-ui/index.html#/
|