Swagger 3 是一个用于描述、构建和测试 RESTful Web 服务的开源工具集。它提供了一种简单而强大的方式来定义和文档化 API 接口,同时还具备自动生成客户端代码和服务器存根代码的功能。
Knife4j是一个集Swagger2 和 OpenAPI3为一体的增强解决方案,其前身是swagger-bootstrap-ui。
组件 | 版本 |
---|---|
springfox | 3.0.0 |
knife4j | 3.0.3 |
Knife4j官网文档表明该版本为过度版本,已经很久没更新,最新版本支持Swagger2规范的springfox 2.10.5版本,在SpringBoot3中只支持OpenAPI3规范,鉴于国内使用Swagger比较广泛,本文以上面版本为例集成API接口文档,后续会以OpenAPI3规范为基础集成API接口文档。
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-boot-starterartifactId>
<version>3.0.0version>
dependency>
<dependency>
<groupId>com.github.xiaoymingroupId>
<artifactId>knife4j-spring-boot-starterartifactId>
<version>3.0.3version>
dependency>
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket docket() {
RequestParameterBuilder parameterBuilder = new RequestParameterBuilder();
List<RequestParameter> parameters = new ArrayList<>();
parameterBuilder.name("commerce-user")
.description("token值")
.in(ParameterType.HEADER)
.required(true)
.build();
parameters.add(parameterBuilder.build());
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.enable(true)//开启Swagger文档
.select()
.apis(RequestHandlerSelectors.basePackage("com.xlhj.commerce"))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
.globalRequestParameters(parameters);
}
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("micro-service")
.description("commerce-service")
.contact(new Contact("xxxx.xxx", "www.xlhj.com.cn", "[email protected]"))
.version("1.0")
.build();
}
}
直接启动项目时会报如下的错误:Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is java.lang.NullPointerException
这是因为Springfox假设Spring MVC的路径匹配策略是 ant-path-matcher,而 Spring Boot 2.6以上版本的默认匹配策略是 path-pattern-matcher,需要加入一下配置
@Configuration
public class BeanPostProcessorConfig {
@Bean
public BeanPostProcessor beanPostProcessor() {
return new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
handlerMappings(getHandlerMappings(bean));
}
return bean;
}
private <T extends RequestMappingInfoHandlerMapping> void handlerMappings(List<T> mappings) {
List<T> copy = mappings.stream()
.filter(mapping -> mapping.getPatternParser() == null)
.collect(Collectors.toList());
mappings.clear();
mappings.addAll(copy);
}
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的静态文件路径放行,配置如下:
@Configuration
public class XlhjWebMvcConfig extends WebMvcConfigurationSupport {
/**
* MVC 加载Swagger静态资源
* @param registry
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/");
registry.addResourceHandler("doc.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
super.addResourceHandlers(registry);
}
}
@Api(tags = "用户地址服务")
@Slf4j
@RestController
@RequestMapping("/address")
public class AddressController {
private final IAddressService addressService;
public AddressController(IAddressService addressService) {
this.addressService = addressService;
}
@ApiOperation(value = "创建", notes = "创建用户地址信息", httpMethod = "POST")
@PostMapping(value = "/create-address")
public TableId createAddressInfo(@RequestBody AddressInfo addressInfo) {
return addressService.createAddressInfo(addressInfo);
}
}
Swagger注解主要分为两大类,一类是用于Controller类,一类用于请求/响应实体类
用于Controller类的注解有:
@Api:描述API接口的基本信息,包括接口名称、描述
@ApiOperation:描述API接口的操作方法,包括HTTP请求方法、接口路径、接口说明
@ApiParam:描述API接口的参数信息,包括参数名称、参数类型、参数说明
用于请求/响应实体类的注解有:
@ApiModel:描述API接口的类信息,包括数据结构和说明
@ApiModelProperty:描述API接口字段属性,包括属性名称、属性类型、属性说明
启动项目,在浏览器访问地址http://127.0.0.1:8003/commerce-account-service/swagger-ui/index.html和http://127.0.0.1:8003/commerce-account-service/doc.html