1. 程式人生 > >SpringBoot整合Swagger2

SpringBoot整合Swagger2

io.springfox springfox-swagger-ui 2.6.1 二、Swagger配置類 其實這個配置類,只要瞭解具體能配置哪些東西就好了,畢竟這個東西配置一次之後就不用再動了。 特別要注意的是裡面配置了api檔案也就是controller包的路徑,不然生成的文件掃描不到介面。

package cn.saytime;

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;

/**

  • @author zh

  • @ClassName cn.saytime.Swgger2

  • @Description

  • @date 2017-07-10 22:12:31 */ @Configuration public class Swagger2 {

    @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage(“cn.saytime.web

    ”)) .paths(PathSelectors.any()) .build(); }

    private ApiInfo apiInfo() { return new ApiInfoBuilder() .title(“springboot利用swagger構建api文件”) .description(“簡單優雅的restfun風格,http://blog.csdn.net/saytime”) .termsOfServiceUrl(“http://blog.csdn.net/saytime”) .version(“1.0”) .build(); } } 用@Configuration註解該類,等價於XML中配置beans;用@Bean標註方法等價於XML中配置bean。

Application.class 加上註解@EnableSwagger2 表示開啟Swagger

package cn.saytime;

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication @EnableSwagger2 public class SpringbootSwagger2Application {

public static void main(String[] args) {
	SpringApplication.run(SpringbootSwagger2Application.class, args);
}

import cn.saytime.bean.JsonResult; import cn.saytime.bean.User; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map;

/**

  • @author zh

  • @ClassName cn.saytime.web.UserController

  • @Description */ @RestController public class UserController {

    // 建立執行緒安全的Map static Map<Integer, User> users = Collections.synchronizedMap(new HashMap<Integer, User>());

    /**

    • 根據ID查詢使用者
    • @param id
    • @return */ @ApiOperation(value=“獲取使用者詳細資訊”, notes=“根據url的id來獲取使用者詳細資訊”) @ApiImplicitParam(name = “id”, value = “使用者ID”, required = true, dataType = “Integer”, paramType = “path”) @RequestMapping(value = “user/{id}”, method = RequestMethod.GET) public ResponseEntity getUserById (@PathVariable(value = “id”) Integer id){ JsonResult r = new JsonResult(); try { User user = users.get(id); r.setResult(user); r.setStatus(“ok”); } catch (Exception e) { r.setResult(e.getClass().getName() + “:” + e.getMessage()); r.setStatus(“error”); e.printStackTrace(); } return ResponseEntity.ok®; }

    /**

    • 查詢使用者列表
    • @return */ @ApiOperation(value=“獲取使用者列表”, notes=“獲取使用者列表”) @RequestMapping(value = “users”, method = RequestMethod.GET) public ResponseEntity getUserList (){ JsonResult r = new JsonResult(); try { List userList = new ArrayList(users.values()); r.setResult(userList); r.setStatus(“ok”); } catch (Exception e) { r.setResult(e.getClass().getName() + “:” + e.getMessage()); r.setStatus(“error”); e.printStackTrace(); } return ResponseEntity.ok®; }

    /**

    • 新增使用者

    • @param user

    • @return */ @ApiOperation(value=“建立使用者”, notes=“根據User物件建立使用者”) @ApiImplicitParam(name = “user”, value = “使用者詳細實體user”, required = true, dataType = “User”) @RequestMapping(value = “user”, method = RequestMethod.POST) public ResponseEntity add (@RequestBody User user){ JsonResult r = new JsonResult(); try { users.put(user.getId(), user); r.setResult(user.getId()); r.setStatus(“ok”); } catch (Exception e) { r.setResult(e.getClass().getName() + “:” + e.getMessage()); r.setStatus(“error”);

       e.printStackTrace();
      

      } return ResponseEntity.ok®; }

    /**

    • 根據id刪除使用者

    • @param id

    • @return */ @ApiOperation(value=“刪除使用者”, notes=“根據url的id來指定刪除使用者”) @ApiImplicitParam(name = “id”, value = “使用者ID”, required = true, dataType = “Long”, paramType = “path”) @RequestMapping(value = “user/{id}”, method = RequestMethod.DELETE) public ResponseEntity delete (@PathVariable(value = “id”) Integer id){ JsonResult r = new JsonResult(); try { users.remove(id); r.setResult(id); r.setStatus(“ok”); } catch (Exception e) { r.setResult(e.getClass().getName() + “:” + e.getMessage()); r.setStatus(“error”);

       e.printStackTrace();
      

      } return ResponseEntity.ok®; }

    /**

    • 根據id修改使用者資訊

    • @param user

    • @return */ @ApiOperation(value=“更新資訊”, notes=“根據url的id來指定更新使用者資訊”) @ApiImplicitParams({ @ApiImplicitParam(name = “id”, value = “使用者ID”, required = true, dataType = “Long”,paramType = “path”), @ApiImplicitParam(name = “user”, value = “使用者實體user”, required = true, dataType = “User”) }) @RequestMapping(value = “user/{id}”, method = RequestMethod.PUT) public ResponseEntity update (@PathVariable(“id”) Integer id, @RequestBody User user){ JsonResult r = new JsonResult(); try { User u = users.get(id); u.setUsername(user.getUsername()); u.setAge(user.getAge()); users.put(id, u); r.setResult(u); r.setStatus(“ok”); } catch (Exception e) { r.setResult(e.getClass().getName() + “:” + e.getMessage()); r.setStatus(“error”);

       e.printStackTrace();
      

      } return ResponseEntity.ok®; }

    @ApiIgnore//使用該註解忽略這個API @RequestMapping(value = “/hi”, method = RequestMethod.GET) public String jsonTest() { return " hi you!"; } } Json格式輸出類 JsonResult.class

package cn.saytime.bean;

public class JsonResult {

private String status = null;

private Object result = null;

// Getter Setter

} 實體User.class

package cn.saytime.bean;

import java.util.Date;

/**

  • @author zh

  • @ClassName cn.saytime.bean.User

  • @Description */ public class User {

    private int id; private String username; private int age; private Date ctm;

    // Getter Setter } 專案結構:

這裡寫圖片描述

這裡寫圖片描述

具體裡面的內容以及介面測試,應該一看就懂了。這裡就不一一截圖了。

五、Swagger註解 swagger通過註解表明該介面會生成文件,包括介面名、請求方法、引數、返回資訊的等等。

@Api:修飾整個類,描述Controller的作用 @ApiOperation:描述一個類的一個方法,或者說一個介面 @ApiParam:單個引數描述 @ApiModel:用物件來接收引數 @ApiProperty:用物件接收引數時,描述物件的一個欄位 @ApiResponse:HTTP響應其中1個描述 @ApiResponses:HTTP響應整體描述 @ApiIgnore:使用該註解忽略這個API @ApiError :發生錯誤返回的資訊 @ApiImplicitParam:一個請求引數 @ApiImplicitParams:多個請求引數