第一步:创建maven工程,添加依赖:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.7</version>
</dependency>
第二步:工程中创建一个配置类Knife4jConfiguration,添加如下的配置
@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.aluphy.material.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
}
注意,这里指定Controller扫描包路径就是你项目中的路径
第三步:添加controller包含一个简单的RESTful接口,代码示例如下:
@Api(tags = "首页模块")
@RestController
public class IndexController {
@ApiImplicitParam(name = "name",value = "姓名",required = true)
@ApiOperation(value = "hello")
@GetMapping("/sayHi")
public ResponseEntity<String> sayHi(@RequestParam(value = "name")String name){
return ResponseEntity.ok("Hi:"+name);
}
}
第四步:启动Spring Boot工程,在浏览器中访问:http://localhost:9010/doc.html
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/26ea3da759017e4cf8ba1d051de6070b.png)
可以看到定义的方法已经在文档中显示出来了.个人感觉比swagger好用
这里需要注意,如果访问不成功,检查你的配置文件是否添加了 context-path 的配置,如果添加了,需要在访问路径中也添加上.
server:
port: 9001
servlet:
context-path: /base
实际上我的访问路径为http://localhost:9010/base/doc.html