以前的文章介紹了《推薦一款接口 API 設計神器!》,今天棧長給你們介紹下如何與優秀的 Spring Boot 框架進行集成,簡直不能太簡單。html
更多請在Java技術棧微信公衆號後臺回覆關鍵字:boot。java
Maven依賴示例:web
<!-- Swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> </dependency>
swagger: title: API標題 description: API描述 version: 1.0 terms-of-service-url: http://www.javastack.cn/ base-package: cn.javastack.test.web contact: name: Javastack url: http://www.javastack.cn/ email: admin@javastack.cn
@Getter @Setter @Configuration @EnableSwagger2 @ConditionalOnClass(EnableSwagger2.class) @ConfigurationProperties(prefix = "swagger") public class SwaggerConfig { /** * API接口包路徑 */ private String basePackage; /** * API頁面標題 */ private String title; /** * API描述 */ private String description; /** * 服務條款地址 */ private String termsOfServiceUrl; /** * 版本號 */ private String version; /** * 聯繫人 */ private Contact contact; @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage(basePackage)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title(title) .description(description) .termsOfServiceUrl(termsOfServiceUrl) .version(version) .contact(contact) .build(); } }
Swagger 默認會根據配置的包,掃描全部接口並生成對應的 API 描述和參數信息,但這樣不是很直觀,須要對每一個接口和參數進行自定義描述。spring
經常使用的 Swagger 註解以下。api
註解名稱 | 使用說明 |
---|---|
@Api | 描述一個 API 類 |
@ApiImplicitParam | 描述一個請求參數 |
@ApiImplicitParams | 描述一組請求參數 |
@ApiModel | 描述一個返回的對象 |
@ApiModelProperty | 描述一個返回的對象參數 |
@ApiOperation | 描述一個 API 方法 |
@ApiParam | 描述一個方法的參數 |
@ApiResponse | 描述一個請求響應 |
@ApiResponses | 描述一組請求響應 |
使用示例如:微信
@Api(description = "登陸模塊") @RestController public class LoginController { @ApiOperation(value = "登陸", httpMethod = "POST") @ApiImplicitParams({ @ApiImplicitParam(name = "username", value = "用戶名", dataType = "string", paramType = "query"), @ApiImplicitParam(name = "password", value = "密碼", dataType = "string", paramType = "query")}) @PostMapping(value = "/login") public Object login(@RequestParam("username") String username, @RequestParam("password") String password) { // ... } }
http://localhost:8080/swagger-ui.html
打開 swagger-ui 界面,能夠看到全部的 API 接口定義,也能夠在上面發起接口測試。app
關注Java技術棧微信公衆號,在後臺回覆:工具,獲取棧長整理的更多的工具絕技,都是實戰乾貨,如下僅爲部分預覽。框架
本文原創首發於微信公衆號:Java技術棧(id:javastack),關注公衆號在後臺回覆 "工具" 可獲取更多,轉載請原樣保留本信息。