什么是Swagger?
Swagger官方网站
是一个规范且完整的框架,提供描述、生产、消费和可视化RESTful Web Service。
是由庞大工具集合支撑的形式化规范。这个集合涵盖了从终端用户接口、底层代码库到商业API管理的方方面面。
如何在Spring boot 项目中整合Swagger?
1.在pom.xml 文件中添加Swagger依赖并更新
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
2.新建Swagger配置类
package com.jelly.test;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* Created by jelly on 2018/1/29.
*/
@Configuration
public class Swagger2 {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.jelly.test"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("Jelly的Swagger-ui")
.description("Jelly is cool")
.termsOfServiceUrl("https://www.jianshu.com/u/43a74b4b7f5d")
.version("1.0.0")
.build();
}
}
3.在Application.class添加注解@EnableSwagger2
package com.jelly.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class GirlApplication {
public static void main(String[] args) {
SpringApplication.run(GirlApplication.class, args);
}
}
4.编写Restful 接口文档
常用注解可以参考这片文章Swagger 常用注解说明,这里是一个简单的用法
@ApiOperation(value = "Post Song List", notes = "Post Song List")
@PostMapping("/omp/karaoke-song")
public ResponseEntity<String> karaokeSongList(@RequestBody @Valid KaraokeSong karaokeSong) {
this.karaokeSongList = karaokeSong;
return new ResponseEntity<>(this.ompController.OMP_CONTROLLER_OK, HttpStatus.OK);
}
启动服务打开网址输入url + swagger-ui.html就可以看到如图界面。
Swagger-ui.png
快去试试吧。
jelly.jpg
网友评论