一、导包
knife4j 主要美化 swagger API 文档,Knife4j 3.0.3 向下兼容支持 swagger2 和 swagger 3,下面简单聊下 springboot 2.6.12 使用 swagger 2(尝试了使用 swagger 3,但是有些注解不能使用,暂时放弃)
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- knife4j -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
二、knife4j 配置
application.properties 配置
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
# 开启增强
knife4j.enable=true
# 生产环境关闭
knife4j.production=false
# 启用登录
knife4j.basic.enable=true
knife4j.basic.username=admin
knife4j.basic.password=123456
spring.mvc.pathmatch.matching-strategy=ant_path_matcher 作用:spring 升级到 5.3.0 之后路径通配的配置发生了变化,我的 springboot 2.6.12, spring 5.3.23,需要配置,否则会报如下错误
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-10-18 14:39:18.268 [ERROR] class:[org.springframework.boot.SpringApplication] 835 reportFailure - Application run failed org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.23.jar:5.3.23]
at java.lang.Iterable.forEach(Iterable.java:75) ~[?:1.8.0_161]
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.12.jar:2.6.12]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:745) ~[spring-boot-2.6.12.jar:2.6.12]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:420) ~[spring-boot-2.6.12.jar:2.6.12]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) ~[spring-boot-2.6.12.jar:2.6.12]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1317) ~[spring-boot-2.6.12.jar:2.6.12]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.6.12.jar:2.6.12]
at com.guowang.CadreReserveApplication.main(CadreReserveApplication.java:12) ~[classes/:?]
三、swagger 配置
swagger 静态资源映射
package com.guowang.config;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* @description:
* @author: Ye
* @date: 2022/10/18 11:31
*/
@Configuration
//@EnableOpenApi 启用 swagger3
@EnableSwagger2
@EnableKnife4j
public class SwaggerWebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/**
* 设置静态资源映射
*/
registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2) // 对于 swagger3 只需要将 DocumentationType.SWAGGER_2 换为DocumentationType.OAS_30 即可
.apiInfo(apiInfo())
.enable(true)
.groupName("ye")
.select()
.apis(RequestHandlerSelectors.basePackage("com.ye.controller"))
.paths(PathSelectors.any())
.build();
}
@SuppressWarnings("all")
public ApiInfo apiInfo() {
return new ApiInfo(
"测试",
"测试-人员信息 api",
"v1.0",
"123456@qq.com", //开发者团队的邮箱
"ye",
"Apache 2.0", //许可证
"http://www.apache.org/licenses/LICENSE-2.0" //许可证链接
);
}
}
拦截器/过滤器 放行 swagger 接口,没有拦截器、过滤器可以不添加
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Autowired
LoginInterceptor loginInterceptor; // 拦截器,主要作用判断 token 有效性
/**
* Description: 拦截接口
* date: 2022/10/14 10:58
* @author: Ye
* @return: void
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor).addPathPatterns("/**")// 拦截所有请求,包括静态资源
.excludePathPatterns("/user/login") // 放行登录接口
.excludePathPatterns("/swagger**/**", "/webjars/**", "/v3/**", "/doc.html", "/v2/**"); // 放行 swagger2、swagger3 接口
}
}
到此简单配置就完了,启动项目访问 http://localhost:8080/doc.html 即可看到 API 文档
四、简单测试
实体类注解
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "用户信息", description = "用户信息实体类")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
/* 用户名 */
@ApiModelProperty(value = "用户名")
private String userName;
/* 密码 */
@ApiModelProperty(value = "密码")
private String password;
/* 类型:管理员:1 | 普通用户:2 */
@ApiModelProperty(value = "用户类型")
private Integer userType;
}
controller 层注解
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {
@ApiOperation(notes = "用户登录",value = "用户登录")
@PostMapping("/login")
public Result<?> login(@RequestBody User user) {
if (null != user.getUserName() && !user.getUserName().isEmpty() && null != user.getPassword() && !user.getPassword().isEmpty()) {
for (User user1 : userUtil.list) {
if (user.getUserName().equals(user1.getUserName()) && user.getPassword().equals(user1.getPassword())) {
String token = tokenUtil.createToken(user);
return Result.OK(user1, token);
}
}
}
return Result.error(ReturnErrorStatusDesc.USER_PASSWORD_CODE);
}
}
查看 swagger 文档,说明 API 文档添加成功
五、swagger 其他注解
swagger2 | OpenAPI 3 | 注解位置 |
---|---|---|
@Api | @Tag(name = “接口类描述”) | Controller 类上 |
@ApiOperation | @Operation(summary =“接口方法描述”) | Controller 方法上 |
@ApiImplicitParams | @Parameters | Controller 方法上 |
@ApiImplicitParam | @Parameter(description=“参数描述”) | Controller 方法上 @Parameters 里 |
@ApiParam | @Parameter(description=“参数描述”) | Controller 方法的参数上 |
@ApiIgnore | @Parameter(hidden = true) 或 @Operation(hidden = true) 或 @Hidden | - |
@ApiModel | @Schema | entity 类上 |
@ApiModelProperty | @Schema | entity 属性上 |