前言
不会还有人不知道swagger是什么吧?
作用:
- 第一点,也是最重要的一点:在个人开发时代,这就是你的装逼神器
- 第二点,也是实际意义上最重要的一点:在前后端分离时代,这是一个不可或缺的前后端交流工具
定义:
- 实际上,他对你的功能没有任何作用,他只是一个接口文档
- 他能自动的生成接口信息,告诉你,这个接口是干什么的,有什么用,需要什么参数
- 改善后的swagger甚至具有调试功能
springboot整合swagger
第一步:新建一个springboot项目
第二步:导入依赖包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
第三步:编写配置文件
- 结合第五步的页面,差不多就知道下面的配置的作用
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* swagger docket实例
* @return
*/
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(true) //是否激活swagger,如果是正式环境下,请把他设置为false
.groupName("赵成默") //分组,可以设置多个docket
.select()
.apis(RequestHandlerSelectors.basePackage("com.zzs.swagger.controller"))
.paths(PathSelectors.any())
.build();
}
public ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("赵成默")
.description("swagger学习")
.version("1.0")
.termsOfServiceUrl("termsOfServiceUrl")
.contact(new Contact("name","url","email"))
.build();
}
// 下面的是默认配置 apiInfo.default
// static {
// DEFAULT = new ApiInfo("Api Documentation", "Api Documentation", "1.0", "urn:tos", DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList());
// }
}
第四步:编写controller层
- 结合第五步的页面,差不多就知道下面的配置的作用,参数非常容易理解
@RestController
public class Controller {
@ApiOperation(value = "你好",notes = "", httpMethod = "POST")
@ApiImplicitParams({
// @ApiImplicitParam(name = "str" ,value = "字符")
})
@RequestMapping("/hello")
public String hello(@ApiParam("字符") String str){
return "hello"+str;
}
}
第五步:启动(访问地址为:http://localhost:8080/swagger-ui.html)
加强版Swagger:knife4j
步骤和上面一样
区别一:pom依赖
<!--swagger-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<!--在引用时请在maven中央仓库搜索最新版本号-->
<version>2.0.4</version>
</dependency>
区别二:访问地址(http://localhost:8080/doc.html)
它强大的地方在于
- UI变好看了
- 他可以进行调试