SpringBoot 项目集成 Swagger 3.0 文档
-
添加依赖
在 SpringBoot 项目中,在 pom 文件中添加 Swagger 3.0 的依赖
<!-- 引入 Swagger 3.0 的依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
-
创建 Swagger 配置类
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
// 文档信息
ApiInfo apiInfo = new ApiInfoBuilder().title("Swagger3 接口文档")
.description("Swagger3 接口文档")
.contact(new Contact("shijialeya", "http://www.shijialeya.top/", "jialeliao24@gmail.com"))
.version("1.0")
.build();
//返回文档摘要信息
return new Docket(DocumentationType.OAS_30)
// 文档信息
.apiInfo(apiInfo)
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(Operation.class))
.paths(PathSelectors.any())
.build();
}
}
-
在 application.properties 文件中添加配置
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
-
创建 Controller 测试接口
创建接口时使用 @Api
注解和 @Operation
注解。
@RestController
@RequestMapping("hello")
@Api(tags = "hello 模块接口")
public class HelloController {
@GetMapping("test")
@Operation(summary = "测试接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "用户名", dataTypeClass = String.class),
@ApiImplicitParam(name = "age", value = "年龄", dataTypeClass = Integer.class)
})
public String test(String name, int age) {
return name + ": " + age + ": " + LocalDateTime.now().toString();
}
}
-
访问查看
启动 SpringBoot 启动类,浏览地址:http://localhost:端口号/swagger-ui/index.html
如果做了访问权限限制,请将 /swagger-ui 下的地址放行,即可看到接口的信息。
SpringBoot 项目集成 knife4j 文档
在以上的基础下,在 pom 文件下添加以下依赖即可:
<!-- knife4j 文档依赖 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.7</version>
</dependency>
如果是 Security 项目,需要增加下面配置类:
@Configuration
public class Knife4jConfig extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
开放接口:
http.authorizeRequests().antMatchers("/swagger**/**", "/webjars/**", "/v3/**", "/doc.html").permitAll();
启动 SpringBoot 启动类,浏览地址:http://localhost:端口号/doc.html