springboot整合Swagger能夠自動生成介面api
阿新 • • 發佈:2018-11-19
1.新增pom
<!--swagger2--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.6</version> </dependency>
2.建立Swagger2
package com.pb.news.servlet; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 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; /** */ @Configuration @EnableSwagger2 public class Swagger2 { /** * 建立API應用 * apiInfo() 增加API相關資訊 * 通過select()函式返回一個ApiSelectorBuilder例項,用來控制哪些介面暴露給Swagger來展現, * 本例採用指定掃描的包路徑來定義指定要建立API的目錄。 * * @return */ @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.pb.news.controller")) .paths(PathSelectors.any()) .build(); } /** * 建立該API的基本資訊(這些基本資訊會展現在文件頁面中) * 訪問地址:http://專案實際地址/swagger-ui.html * 訪問地址:http://專案實際地址/doc.html(美化) * @return */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("APIs") .description("所有controller的介面") .termsOfServiceUrl("") .contact("pb") .version("1.0") .build(); } }
3.修改controller
@RestController //代表controller @RequestMapping("/userC") @Api(value = "使用者的處理")//新增描述 public class UserController { @RequestMapping(value="/userLogin",method = RequestMethod.POST) @ResponseBody @ApiOperation(value = "使用者進行shiro登入")//方法名稱描述 //@ApiImplicitParam(paramType = "query",name= "username" ,value = "使用者名稱",dataType = "string")//單個引數 //多個引數 @ApiImplicitParams({ @ApiImplicitParam(paramType = "query",name= "username" ,value = "使用者名稱",dataType = "string"), @ApiImplicitParam(paramType = "query",name= "password" ,value = "密碼",dataType = "string") }) /*public void userLogin(@RequestParam(value = "username" , required = false) String username, @RequestParam(value = "password" , required = false) String password)*/ public void userLogin(@RequestBody JSONObject json){ } }
最後:
http://localhost:8090/swagger-ui.html 是標準版
http://localhost:8090/doc.html 是添加了美化的ui後首頁
效果如圖
參考資料: