springboot集成swagger

1、加入依賴css

<dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.7.0</version>
            </dependency>
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.7.0</version>
            </dependency>

2、建立Swagger2配置類html

package com.sxdx.oa_service.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
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 SwaggerConfiguration {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //.apis(RequestHandlerSelectors.basePackage("com.sxdx.oa_service"))//配置須要生成文檔的掃碼路徑
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))//配置須要生成文檔的類型,此處爲全部添加了@RestController註解的類
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("RESTful APIs")
                .description("oa_frame 接口文檔")
                //.termsOfServiceUrl("http://easonjim.com/")
                .contact("高一鵬")
                .version("1.0")
                .build();
    }
}

3、代碼示例java

package com.sxdx.oa_service.springCacheTest.controller;

import com.sxdx.oa_service.bootTest.bean.JsonResult;
import com.sxdx.oa_service.springCacheTest.model.Department;
import com.sxdx.oa_service.springCacheTest.service.CacheTestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(value = "緩存練習接口",tags = {"緩存練習接口"},description="用於練習spring緩存及redis",hidden = false)
public class CacheTestController {
    @Autowired
    private CacheTestService cacheTestService;

    @ApiOperation(
            value = "經過id查詢部門信息",
            notes="經過id查詢部門信息")
    @GetMapping(value = "selectDeptById/{id}")
    public ResponseEntity<JsonResult> selectByPrimaryKey(@PathVariable Integer id){
        JsonResult r = new JsonResult();
        try {
            Department department = cacheTestService.selectByPrimaryKey(id);
            r.setResult(department);
            r.setStatus("success");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("failure");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }


    @ApiOperation(value = "修改部門信息", notes="修改部門信息")
    @PostMapping(value = "updateByPrimaryKeySelective")
    public ResponseEntity<JsonResult> updateByPrimaryKeySelective(@RequestBody Department dept){
        JsonResult r = new JsonResult();
        try {
            Department department = cacheTestService.updateByPrimaryKeySelective(dept);
            r.setResult(department);
            r.setStatus("success");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("failure");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }


    @ApiOperation(value = "經過id 刪除部門", notes="經過id 刪除部門")
    @GetMapping (value = "deleteDeptById/{id}")
    public ResponseEntity<JsonResult> updateByPrimaryKeySelective(@PathVariable Integer id){
        JsonResult r = new JsonResult();
        try {
            int num = cacheTestService.deleteByPrimaryKey(id);
            r.setResult("已刪除");
            r.setStatus("success");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("failure");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
}

4、生成的文檔效果(http://127.0.0.1:8080/oaframe/swagger-ui.html)web

 

5、各個註解的介紹(轉載自https://www.cnblogs.com/hyl8218/p/8520994.html)redis

經常使用到的註解有:
  • Api
  • ApiModel
  • ApiModelProperty
  • ApiOperation
  • ApiParam
  • ApiResponse
  • ApiResponses
  • ResponseHeader
1. api標記

Api 用在類上,說明該類的做用。能夠標記一個Controller類作爲swagger 文檔資源,使用方式:spring

@Api(value = "/user", description = "Operations about user") 

與Controller註解並列使用。 屬性配置:json

屬性名稱 備註
value url的路徑值
tags 若是設置這個值、value的值會被覆蓋
description 對api資源的描述
basePath 基本路徑能夠不配置
position 若是配置多個Api 想改變顯示的順序位置
produces For example, "application/json, application/xml"
consumes For example, "application/json, application/xml"
protocols Possible values: http, https, ws, wss.
authorizations 高級特性認證時配置
hidden 配置爲true 將在文檔中隱藏

在SpringMvc中的配置以下:api

@Controller @RequestMapping(value = "/api/pet", produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE}) @Api(value = "/pet", description = "Operations about pets") public class PetController { } 
2. ApiOperation標記

ApiOperation:用在方法上,說明方法的做用,每個url資源的定義,使用方式:緩存

@ApiOperation( value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order, tags = {"Pet Store"}) 

與Controller中的方法並列使用。
屬性配置:ruby

屬性名稱 備註
value url的路徑值
tags 若是設置這個值、value的值會被覆蓋
description 對api資源的描述
basePath 基本路徑能夠不配置
position 若是配置多個Api 想改變顯示的順序位置
produces For example, "application/json, application/xml"
consumes For example, "application/json, application/xml"
protocols Possible values: http, https, ws, wss.
authorizations 高級特性認證時配置
hidden 配置爲true 將在文檔中隱藏
response 返回的對象
responseContainer 這些對象是有效的 "List", "Set" or "Map".,其餘無效
httpMethod "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH"
code http的狀態碼 默認 200
extensions 擴展屬性

在SpringMvc中的配置以下:

@RequestMapping(value = "/order/{orderId}", method = GET) @ApiOperation( value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags = { "Pet Store" }) public ResponseEntity<Order> getOrderById(@PathVariable("orderId") String orderId) throws NotFoundException { Order order = storeData.get(Long.valueOf(orderId)); if (null != order) { return ok(order); } else { throw new NotFoundException(404, "Order not found"); } } 
3. ApiParam標記

ApiParam請求屬性,使用方式:

public ResponseEntity<User> createUser(@RequestBody @ApiParam(value = "Created user object", required = true) User user) 

與Controller中的方法並列使用。

屬性配置:

屬性名稱 備註
name 屬性名稱
value 屬性值
defaultValue 默認屬性值
allowableValues 能夠不配置
required 是否屬性必填
access 不過多描述
allowMultiple 默認爲false
hidden 隱藏該屬性
example 舉例子

在SpringMvc中的配置以下:

public ResponseEntity<Order> getOrderById(
      @ApiParam(value = "ID of pet that needs to be fetched", allowableValues = "range[1,5]", required = true) @PathVariable("orderId") String orderId) 
4. ApiResponse

ApiResponse:響應配置,使用方式:

@ApiResponse(code = 400, message = "Invalid user supplied") 

與Controller中的方法並列使用。 屬性配置:

屬性名稱 備註
code http的狀態碼
message 描述
response 默認響應類 Void
reference 參考ApiOperation中配置
responseHeaders 參考 ResponseHeader 屬性配置說明
responseContainer 參考ApiOperation中配置

在SpringMvc中的配置以下:

@RequestMapping(value = "/order", method = POST) @ApiOperation(value = "Place an order for a pet", response = Order.class) @ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") }) public ResponseEntity<String> placeOrder( @ApiParam(value = "order placed for purchasing the pet", required = true) Order order) { storeData.add(order); return ok(""); } 
5. ApiResponses

ApiResponses:響應集配置,使用方式:

@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") }) 

與Controller中的方法並列使用。 屬性配置:

屬性名稱 備註
value 多個ApiResponse配置

在SpringMvc中的配置以下:

@RequestMapping(value = "/order", method = POST) @ApiOperation(value = "Place an order for a pet", response = Order.class) @ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") }) public ResponseEntity<String> placeOrder( @ApiParam(value = "order placed for purchasing the pet", required = true) Order order) { storeData.add(order); return ok(""); } 
6. ResponseHeader

響應頭設置,使用方法

@ResponseHeader(name="head1",description="response head conf") 

與Controller中的方法並列使用。 屬性配置:

屬性名稱 備註
name 響應頭名稱
description 頭描述
response 默認響應類 Void
responseContainer 參考ApiOperation中配置

在SpringMvc中的配置以下:

@ApiModel(description = "羣組") 
7. 其餘
  • @ApiImplicitParams:用在方法上包含一組參數說明;
  • @ApiImplicitParam:用在@ApiImplicitParams註解中,指定一個請求參數的各個方面
    • paramType:參數放在哪一個地方
    • name:參數表明的含義
    • value:參數名稱
    • dataType: 參數類型,有String/int,無用
    • required : 是否必要
    • defaultValue:參數的默認值
  • @ApiResponses:用於表示一組響應;
  • @ApiResponse:用在@ApiResponses中,通常用於表達一個錯誤的響應信息;
    • code: 響應碼(int型),可自定義
    • message:狀態碼對應的響應信息
  • @ApiModel:描述一個Model的信息(這種通常用在post建立的時候,使用@RequestBody這樣的場景,請求參數沒法使用@ApiImplicitParam註解進行描述的時候;
  • @ApiModelProperty:描述一個model的屬性。
相關文章
相關標籤/搜索