Spring Boot中使用Swagger2構建RESTful APIs介紹

Tidetrace發表於2019-05-20

1、新增相關依賴

   <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>

2、建立Swagger自動配置類


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;

@Configuration
@EnableSwagger2
public class Swagger {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.ck.demo"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2構建RESTful APIs")
                .description("更多Spring Boot相關文章請關注:https://www.yuque.com/chaohen")
                .termsOfServiceUrl("https://www.yuque.com/chaohen")
                .contact("潮痕")
                .version("1.0.0")
                .build();
    }
}
  • 首先通過@Configuration註解,讓Spring來載入該類配置。再通過@EnableSwagger2註解來啟用Swagger2。
  • 其次通過createRestApi函式建立Docket的Bean之後,使用apiInfo()用來建立該Api的基本資訊(這些基本資訊會展現在文件頁面中)。-
  • 再次通過select()函式返回一個ApiSelectorBuilder例項用來控制哪些介面暴露給Swagger來展現,本例採用指定掃描的包路徑來定義,Swagger會掃描該包下所有Controller定義的API,併產生文件內容,這裡除了被@ApiIgnore指定的請求。

實際使用:

import com.ck.demo.bean.BlogsUserInfo;
import com.ck.demo.service.UserInfoService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("user")
public class UsreInfoController {
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation(value = "獲取使用者列表",notes = "")
    @RequestMapping(value = "/getusers",method = RequestMethod.GET)
    public Object getDbType() {
        String sql = "select * from blogs_user_info";
        RowMapper<BlogsUserInfo> rowMapper = new BeanPropertyRowMapper<BlogsUserInfo>(BlogsUserInfo.class);
        List<BlogsUserInfo> list = jdbcTemplate.query(sql, rowMapper);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        Integer times = (Integer) request.getSession().getAttribute("times");
        ;
        if (times == null) {
            times = new Integer(1);
        } else {
            times = new Integer(times.intValue() + 1);
        }
        request.getSession().setAttribute("times", times);
        System.out.println("***********************" + times);
        return list;
    }

    @ApiOperation(value = "根據使用者ID獲取使用者資訊",notes = "")
    @ApiImplicitParam(name = "id", value = "使用者ID", required = true, dataType = "Long")
    @RequestMapping("/getId/{id}")
    public Object getUserInfoByParmityKey(@PathVariable String id) {
        BlogsUserInfo blogsUserInfo = userInfoService.getUserInfoByParmityKeyService(id);
        return blogsUserInfo;
    }

}

註解語法用例:

@Api:用在請求的類上,表示對類的說明
    tags="說明該類的作用,可以在UI介面上看到的註解"
    value="該引數沒什麼意義,在UI介面上也看到,所以不需要配置"
    
eg: @Api(tags = "使用者資訊Controller")



@ApiOperation:用在請求的方法上,說明方法的用途、作用
    value="說明方法的用途、作用"
    notes="方法的備註說明"
    
eg: @ApiOperation(value="使用者登入",notes="手機號、密碼都是必填!")



@ApiImplicitParams:用在請求的方法上,表示一組引數說明
    @ApiImplicitParam:用在@ApiImplicitParams註解中,指定一個請求引數的各個方面
        name:引數名
        value:引數的漢字說明、解釋
        required:引數是否必須傳
        paramType:引數放在哪個地方
            · header --> 請求引數的獲取:@RequestHeader
            · query --> 請求引數的獲取:@RequestParam
            · path(用於restful介面)--> 請求引數的獲取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:引數型別,預設String,其它值dataType="Integer"       
        defaultValue:引數的預設值
        
 eg: @ApiImplicitParams({
        @ApiImplicitParam(name="username",value="使用者名稱",required=true,paramType="String"),
        @ApiImplicitParam(name="password",value="密碼",required=true,paramType="form"),
        @ApiImplicitParam(name="vcode",value="驗證碼",required=true,paramType="form",dataType="Integer")
        })



@ApiResponses:用在請求的方法上,表示一組響應
    @ApiResponse:用在@ApiResponses中,一般用於表達一個錯誤的響應資訊
        code:數字,例如400
        message:資訊,例如"請求引數沒填好"
        response:丟擲異常的類
        
 eg:@ApiOperation(value = "select1請求",notes = "多個引數,多種的查詢引數型別")
     @ApiResponses({
        @ApiResponse(code=400,message="請求引數沒填好"),
        @ApiResponse(code=404,message="請求路徑沒有或頁面跳轉路徑不對")
         })

 
@ApiModel:用於響應類上,表示一個返回響應資料的資訊
            (這種一般用在post建立的時候,使用@RequestBody這樣的場景,
            請求引數無法使用@ApiImplicitParam註解進行描述的時候)
    @ApiModelProperty:用在屬性上,描述響應類的屬性

eg: 
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import java.io.Serializable;

    @ApiModel(description= "返回響應資料")
    public class RestMessage implements Serializable{

        @ApiModelProperty(value = "是否成功")
        private boolean success=true;
        @ApiModelProperty(value = "返回物件")
        private Object data;
        @ApiModelProperty(value = "錯誤編號")
        private Integer errCode;
        @ApiModelProperty(value = "錯誤資訊")
        private String message;

        /* getter/setter */
    }

3、在Swagger視覺化介面展示

輸入 http://localhost:8080/user/getusers  結果如下:

{"uuid":"d882f714-c015-4c46-a92e-5d7e2a8b3380","name":"丫丫","age":12,"address":"浙江省","phone":"1898*****63","company":"alibaba"}

在瀏覽器開啟:http://localhost:8080/swagger-ui.html
頁面如下:
image.png

詳細資訊:

get請求

image.png

post請求

image.png

delete請求

image.png

4、詳情測試

get請求測試:

image.png

post請求測試

image.png

此時執行成功,已經達到所需的目標,End。

相關文章