Springboot2整合knife4j过程解析这玩艺就swagger的升级版,但是⽤起来⽐swagger⽅便多了,⾄少不会出现莫名的版本兼容问题
下⾯记录⼀个配置⽰例
1.代码结构
l
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId&le</groupId>
<artifactId>knife4j-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>knife4j-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<!--在引⽤时请在maven中央仓库搜索最新版本号-->
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.配置类
ample.fig;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import t.annotation.Bean;
import t.annotation.Configuration;
import t.annotation.Import;
import springfox.figuration.BeanValidatorPluginsConfiguration;
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.EnableSwagger2;
@Configuration
@EnableSwagger2
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfiguration {
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//分组名称
.groupName("2.X版本")
.select()
/
/这⾥指定Controller扫描包路径(项⽬路径也⾏)
.apis(RequestHandlerSelectors.basePackage("ample.knife4j.demo"))
.paths(PathSelectors.any())
.build();
return docket;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("不重要")
.description("测试名称不重要")
.termsOfServiceUrl("localhost:88888/")
.
contact("10086@mail")
.version("1.0")
.build();
}
}
4.模型bean
ample.knife4j.demo.beans;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* 创建时间: 23:09 2018/9/19
* 修改时间:
* 编码⼈员: ZhengQf
* 版本: 0.0.1
* 功能描述:
*/
@ApiModel(value = "⽤户模型")
public class UserEntity {
@ApiModelProperty(value="id" ,required= true,example = "123")
private Integer id;
@ApiModelProperty(value="⽤户姓名" ,required=true,example = "郑钦锋")
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "DemoDoctor [id=" + id + ", name=" + name + "]";
}
}
5.两个接⼝controller
ample.ller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(value = "IndexController测试接⼝")
@RestController
public class IndexController {
@ApiOperation(value = "测试index接⼝", nickname = "测试IndexController的index接⼝")  @GetMapping("/index")
public String index() {
return "测试IndexController的index接⼝...";
}
}
ample.ller;
ample.knife4j.demo.beans.UserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
@Api(value = "⽤户接⼝")
@RestController
public class UserController {
@ApiOperation(value = "获取⽤户信息接⼝", nickname = "根据⽤户ID获取⽤户相关信息")  @ApiImplicitParam(name = "id", value = "⽤户ID", required = true, dataType = "int")
@PostMapping("/postMember")
public UserEntity postMember(@RequestParam Integer id) {
UserEntity userEntity = new UserEntity();
userEntity.setId(id);
userEntity.setName("admin");
return userEntity;
}
@ApiOperation(value = "添加⽤户", nickname = "添加⽤户接⼝1", notes = "⼊参是复杂对象", produces = "application/json")
@PostMapping("/postUser")
@ResponseBody
@ApiImplicitParam(paramType = "query", name = "userId", value = "⽤户id", required = true, dataType = "int")
public UserEntity postUser(@RequestBody UserEntity user, @RequestParam("userId") int userId) { //
这⾥⽤包装类竟然报错
if (Id() == userId) {
return user;
}
return new UserEntity();
}
@ApiOperation(value = "添加⽤户", nickname = "添加⽤户接⼝2", notes = "⼊参是简单对象", produces = "application/json")
@PostMapping("/addUser")
@ResponseBody
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "userName", value = "⽤户姓名", required = true, dataType = "String"),
@ApiImplicitParam(paramType = "query", name = "id", value = "⽤户id", required = true, dataType = "int")})
public UserEntity addUser(String userName, int id) {
UserEntity userEntity = new UserEntity();
userEntity.setName(userName);
userEntity.setId(id);
return userEntity;
}
}
6.srpingboot项⽬启动类
ample.knife4j.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.dition.ConditionalOnClass;
import org.springframework.fig.annotation.ResourceHandlerRegistry;
import org.springframework.fig.annotation.WebMvcConfigurer;
import springfox.documentation.spring.web.SpringfoxWebMvcConfiguration;
@ConditionalOnClass(SpringfoxWebMvcConfiguration.class)
@SpringBootApplication
public class Knife4jDemoApplication implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(Knife4jDemoApplication.class, args);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
不过,在项⽬中我使⽤了ResponseBodyAdvice接⼝对项⽬接⼝响应内容做统⼀处理,然后使⽤knife4j就出问题了。
ResponseBodyAdvice接⼝实现如下:
import t.annotation.Configuration;
import MethodParameter;
import org.springframework.http.MediaType;
import org.verter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.fig.annotation.EnableWebMvc;
import org.springframework.web.hod.annotation.ResponseBodyAdvice;
/**
* ⾃定义advise ,对restful请求响应体进⾏统⼀规范
*/
@EnableWebMvc
@Configuration
@RestControllerAdvice
public class ResponseAdvise implements ResponseBodyAdvice<Object> {
@Override
spring framework版本public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object object, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHt
tpRequest request, ServerHttpResponse response) {    if (object instanceof ResponseData) {
return object;
}
return ResponseData.of().setData(object);
}
}
请求报错
⽽且后台还说不到映射路径
2020-03-10 23:31:01.533 WARN 7940 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound : No mapping for GET /service-worker.js 2020-03-10 23:31:01.560 WARN 7940 --- [nio-8080-exec-4] o.s.web.servlet.PageNotFound : No mapping for GET /favicon.ico 2020-03-10 23:31:14.468 WARN 7940 --- [nio-8080-exec-8] o.s.web.servlet.PageNotFound : No mapping for GET /service-worker.js 然后,我在ResponseAdvise#beforeBodyWrite⽅法中打上断点,发现我将swagger的请求内容进⾏了修改,以⾄于报了404。
最后在ResponseAdvise类上声明只对本项⽬的响应体内容进⾏统⼀处理
@RestControllerAdvice(basePackages = "ample.knife4j.demo")
这样,就完全ok!
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。