更多關(guān)于Java方面的文章,歡迎訪問燕歸來https://www.zhoutao123.com
手寫Api文檔的幾個痛點:
- 文檔需要更新的時候,需要再次發(fā)送一份給前端烟阐,也就是文檔更新交流不及時疏橄。
- 接口返回結(jié)果不明確
- 不能直接在線測試接口摇予,通常需要使用工具抱婉,比如postman
- 接口文檔太多,不好管理
Swagger也就是為了解決這個問題程奠,當(dāng)然也不能說Swagger就一定是完美的,當(dāng)然也有缺點祭钉,最明顯的就是代碼移入性比較強瞄沙,需要手動添加注解。其他的不多說慌核,想要了解Swagger的距境,可以去Swagger官網(wǎng),可以直接使用Swagger editor編寫接口文檔垮卓,當(dāng)然我們這里講解的是SpringBoot整合Swagger2垫桂,直接生成接口文檔的方式。
Maven引入依賴項目
<!--Swagger 框架-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<!--Swagger UI-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
配置文件
在Spring中引入Bean,使用Java代碼的方式粟按,更加的方便注意:使用的注解信息
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* 本文件由周濤創(chuàng)建,位于com.tao.mybatis_plus.config包下
* 創(chuàng)建時間2018/3/24 19:04
* 郵箱:zhoutao@xiaodouwangluo.com
* 作用:暫未填寫
*
* @author tao
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//設(shè)置掃描的包名
.apis(RequestHandlerSelectors.basePackage("com.tao.mybatis_plus.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//文檔內(nèi)容配置信息
.title("SpringBoot整合Swagger")
.description("這是一個簡單的SpringBoot項目诬滩,基于Maven架構(gòu),SSM框架搭建")
.termsOfServiceUrl("https://www.zhoutao123.com")
.version("1.0")
.build();
}
}
配置Controller
下面的代碼中主要用到了5個注解分別是:
- RestController
- RequestMapping
- Autowired
- GetMapping
- ApiOperation
其中主要重點介紹ApiOperation
@RestController
@RequestMapping("/book")
public class IndexController {
@Autowired
private IBookService bookServer;
/**
* 查詢圖書列表
* @param index 索引
* @param page 數(shù)量
* @return String
*/
@ApiOperation(value = "查詢圖書列表",notes = "根據(jù)歷史信息查詢結(jié)果")
@GetMapping("/list/{index}/{page}")
public String index(@PathVariable("index") int index,@PathVariable("page") int page){
Integer a = Integer.parseInt("123");
Page<Book> bookPage = bookServer.selectPage(new Page<Book>(index, page));
return JSONObject.toJSONString(bookPage).toString();
}
}
更多關(guān)于Java方面的文章,歡迎訪問燕歸來https://www.zhoutao123.com