1、Knife介绍
黑豹程序员-架构师学习路线图-百科:Knife4j API接口文档管理
2、坐标
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.7</version>
</dependency>
3、和SpringBoot整合
package com.hello.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.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.hello.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API文档")
.description("这是一个示例API文档")
.version("1.0")
.build();
}
}
4、和SpringMVC整合
package com.hello.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* @version v1.0 创建时间:13:38
* @author: 作者:陈子枢
* @web CSDN:https://blog.csdn.net/nutony
* @description 描述:放行Knife4j请求
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
5、使用Swagger注解
package com.hello.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @version v1.0 创建时间:13:04
* @author: 作者:陈子枢
* @web CSDN:https://blog.csdn.net/nutony
* @description 描述:
*/
@RestController
@Api(tags = "用户管理")
public class ApiController {
@ApiOperation("获取用户列表")
@PostMapping("/user/list")
public List getUserList(){
return null;
}
@ApiOperation("获取用户名")
@GetMapping("/user/{name}")
public String getName(@PathVariable String name){
return name;
}
}
6、整合效果
整合后直接访问doc.html链接:http://localhost:8080/doc.html