SpringBoot整合Swagger2簡單的例子
阿新 • • 發佈:2018-01-22
設定 tro -c fault rip comment sed itl java
Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作為服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。Swagger 讓部署管理和使用功能強大的API從未如此簡單。
這裏我給大家帶來一個簡單的整合DEMO 先來看項目結構
下面是基本的步驟
一.添加MAVEN依賴
- <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>org.codehaus.jackson</groupId>
- <artifactId>jackson-core-asl</artifactId>
- <version>1.9.13</version>
- </dependency>
二.編寫Swagger配置類
- @Configuration
- @EnableSwagger2
- public class Swaggers {
- @Bean
- public Docket swaggerSpringMvcPlugin() {
- ApiInfo apiInfo = new ApiInfo("sample of springboot", "sample of springboot", null, null, null, null, null);
- Docket docket = new Docket(DocumentationType.SWAGGER_2).select().paths(regex("/user/.*")).build()
- .apiInfo(apiInfo).useDefaultResponseMessages(false);
- return docket;
- }
- /*private ApiInfo apiInfo() {
- return new ApiInfoBuilder().title("測試API")
- .description("樊亞的測試API1")
- .version("1.0.0")
- .build();
- }*/
- /* @Bean
- public Docket createRestApi() {
- return new Docket(DocumentationType.SWAGGER_2)
- .apiInfo(apiInfo())
- .select()
- .apis(RequestHandlerSelectors.basePackage("com.didispace.web"))
- .paths(regex("/user/.*"))
- .build();
- }
- */
- }
當然也可以用鏈式編程的方法實現,這裏我使用的是NEW
三.編寫Controller
- @RestController
- @RequestMapping("/user")
- @Api(value = "Shop")
- public class SpringBootController {
- @ApiOperation(value = "獲取helloWorld", notes = "簡單SpringMVC請求")
- @RequestMapping("/")
- String home() {
- return "HELLO WORLD";
- }
- @ApiOperation(value = "獲得A+B", notes = "根據url的classNo和url的studentName獲得請求參數的字符串相加,RestFul風格的請求")
- @ApiImplicitParams({@ApiImplicitParam(name = "classNo", value = "班級編號", required = true, dataType = "String"),
- })
- @RequestMapping(value = "/class/{classNo}/to/{studentName}", method = RequestMethod.GET)
- String world(@PathVariable("classNo") String classNo, @PathVariable("studentName") String studentName) {
- return classNo + " " + studentName;
- }
- }
四.編寫Application載入類
- @SpringBootApplication
- public class Application {
- public static void main(String[] args) {
- SpringApplication.run(Application.class,args);
- }
- }
Swagger會默認把所有Controller中的RequestMapping方法都生成API出來,實際上我們一般只需要標準接口的(像返回頁面的那種Controller方法我們並不需要),所有你可以按下面的方法來設定要生成API的方法的要求。
至此功能基本實現了,我們可以通過訪問地址http://localhost:8080/swagger-ui.html/
查看生成好的API
SpringBoot整合Swagger2簡單的例子