SpringBoot集成Knife4j
添加pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
新增配置类Knif4jConfiguration
法一:使用@EnableSwagger2WebMvc
/**
* @author Hmoumou
* @DATE 2021/11/3
* @apiNote
*/
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
//.title("swagger-bootstrap-ui-demo RESTful APIs")
.description("# swagger-bootstrap-ui-demo RESTful APIs")
.termsOfServiceUrl("http://www.xx.com/")
.contact("xx@qq.com")
.version("1.0")
.build())
//分组名称
.groupName("2.X版本")
.select()
//这里指定Controller扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.springweb.demo3.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
}
法二
很奇怪的问题,有一次项目使用上面的注解出现
Knife4j文件请求异常
遂改用如下配置,问题消失;
/**
* @author Hmoumou
* @DATE 2021/11/3
* @apiNote
*/
@Configuration
@EnableSwagger2
@EnableKnife4j
public class Knife4jConfiguration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.apiInfo(apiInfo())
.groupName("1.0版本")
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("test")
.description("后端APIS")
.termsOfServiceUrl("http://localhost:9999/")
.contact("test@qq.com")
.version("1.0")
.build();
}
}
使用
/**
* @author Hmoumou
* @DATE 2021/11/3
* @apiNote
*/测试模块")
@RestController
public class IndexController {
@ApiImplicitParam(name = "name",value = "姓名",required = true)
@ApiOperation(value = "测试")
@GetMapping("/test")
public ResponseEntity<String> sayHi(@RequestParam(value = "name")String name){
return ResponseEntity.ok("Hi:"+name);
}
}
启动
配置完毕后,访问eghttp://localhost:9999/doc.html