springboot集成swagger
一 Swagger2介绍
Swagger是一款RESTful接口的文档在线自动生成、功能测试功能框架。一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务,加上swagger-ui,可以有很好的呈现。
二、SpringBoot集成
这里选用的swagger版本为:2.8.0
2.1.1 pom依赖
<!--swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
2.1.2 编写配置文件(Swagger2Config.java)
主要是添加注解@EnableSwagger2和定义Docket的bean类。
@Configuration
@EnableSwagger2
public class SwaggerConfig {
//是否开启swagger,正式环境一般是需要关闭的,可根据springboot的多环境配置进行设置
@Value(value = “${swagger.enabled}”)
Boolean swaggerEnabled;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
// 是否开启
.enable(swaggerEnabled).select()
// 扫描的路径包
.apis(RequestHandlerSelectors.basePackage("com.example"))
// 指定路径处理PathSelectors.any()代表所有的路径
.paths(PathSelectors.any()).build().pathMapping("/");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot-Swagger2集成和使用-demo示例")
.description("Springboot学习")
// 作者信息
.contact(new Contact("强周亮", "url:https://blog.csdn.net/qq_30192407", "2538096489@qq.com"))
.version("1.0.0")
.build();
}
}
2.1.2.1 swagger.enabled配置在配置文件里面配置自定义(XXX.yml)
swagger:
enabled: true
2.1.3、添加文档内容
@Api(tags = “测试”)
@RestController
@RequestMapping("/demoController")
public class DemoController {
@RequestMapping("helloWorld")
@ApiOperation(value="输出HelloWorld")
public String getHelloWorld(String name){
return "hello World"+names+";
}
}
2.1.4 访问与使用
api首页路径:http://127.0.0.1:8080/swagger-ui.html
2.1.5 调试
点击需要访问的api列表,点击try it out!按钮,即可弹出一下页面:
执行 execute
3 Swagger常用属性说明
常用的注解@Api、@ApiOperation、@ApiModel、@ApiModelProperty示例中有进行标注,对于其他注解,大家可自动谷歌,毕竟常用的就这几个了。有了swagger之后,原本一些post请求需要postman这样的调试工具来进行发起,而现在直接在页面上就可以进行调试了,是不是很爽!对于服务的调用者而已,有了这份api文档也是一目了然,不需要和后端多少沟通成本,按着api说明进行前端开发即可。