管理在线文档的插件有很多,例如swagger。
我这里使用Knife4j,knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案,更利于前后端使用。
引入jar包
com.github.xiaoymin knife4j-spring-boot-starter 3.0.3配置文件
@Configuration
public class Knife4jConfiguration {
@Bean
public Docket defaultApi() {
Docket docket = new Docket(DocumentationType.SWAGGER_2).enable(true).apiInfo(this.apiInfo()).groupName("user").select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.any())
.paths(PathSelectors.regex("(?!/error.*).*")).build();
return docket;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("系统接口文档").description("").version("1.0").build();
}
}
效果
启动项目后,在浏览器中输入 http://127.0.0.1:8888/doc.html,效果如下
上面是获取项目所有的API,但是当项目很大时,这样处理就不太友好了,就需要通过分组的方式显示API,方法很简单
@Bean
public Docket userApi() {
Docket docket = new Docket(DocumentationType.SWAGGER_2).enable(true).apiInfo(this.apiInfo()); docket.groupName("user").select().apis(RequestHandlerSelectors.basePackage("com.hnexm.controller.user")).paths(PathSelectors.any()).build();
return docket;
}
要分几个组就写几个对应的方法即可,如果需要分组,在搭建项目时,将controller按照不同的分组存放到不同的包路径下
登录验证
默认没有设置用户名密码时,只要输入上面的地址就可以直接查看,在开发过程中没问题,但是项目上线后肯定不行,我们在项目配置文件yml中设置开启登录验证即可。
knife4j:
# 是否开启加强模式 true开启 false关闭
enable: true
setting:
# 是否开启调试功能 true开启 false关闭
enableDebug: true
basic:
# 是否开启认证功能 true开启 false关闭
enable: true
username: admin
password: 123456
这样就需要输入用户名,密码才能打开了