本文将讲解, spring boot 和 Swagger2的使用。
1. 版本说明
spring boot 使用的是1.5.x 版本, 因为是和dubbo-spring-boot 结合所以是这个版
dubbo 官方图:
swagger2 使用的是2.7.0 版本
2. 依赖和配置
- 依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
- config 配置
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.zzf.consumer.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("")
.description("")
.termsOfServiceUrl("")
.version("1.0.0")
.build();
}
}
3. 配置说明:
通过@Configuration注解来加载该类配置。再通过@EnableSwagger2注解来启用Swagger2。
通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。
在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,而描述主要来源于函数等命名产生,对用户并不友好,我们通常需要自己增加一些说明来丰富文档内容。如下所示,我们通过@ApiOperation注解来给API增加说明、通过@ApiImplicitParams、@ApiImplicitParam注解来给参数增加说明。
4. 使用介绍:
controller 上添加上相应的信息
@Controller
public class SimpleConsumerController {
@Reference
private SimpleInterface simpleInterface;
@ApiOperation(value = "统一调用", notes = "统一调用", produces = "application/json")
@RequestMapping("/unify")
public String unify(String name){
return simpleInterface.unify(name);
}
}
启动Spring Boot程序,访问:http://localhost:8080/swagger-ui.html
参考文章 :
https://blog.csdn.net/gxk1992/article/details/78774340
https://blog.csdn.net/youzhouliu/article/details/53925174