SpringBoot入門教程六:Springboot集成Swagger2

Swagger2簡介

Swagger2是Api接口文檔生成工具,它作爲一個規範和完整的框架,可以用於生成、描述、調用和可視化 RESTful 風格的 Web 服務:

  1. 接口文檔在線自動生成,文檔隨接口變動實時更新,節省維護成本

  2. 支持在線接口測試,不依賴第三方工具

 

步驟

(1)在pom.xml文件中引入相關依賴;

(2)創建Swagger2配置類Swagger2Configuration ;

(3)編寫API測試接口;

(4)啓動Springboot應用,查看接口文檔;

(5)測試接口。

 

 

>>>>>>>>>>>>>>>>>>>>>開始>>>>>>>>>>>>>>>>>>>>>>>>

1、加入相關依賴

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

 

2、創建Swagger2配置類Swagger2Configuration 

@Configuration
@EnableSwagger2
public class Swagger2Configuration {

    //api接口包掃描路徑
    public static final String SWAGGER_SCAN_BASE_PACKAGE = "org.lee.springboot";

    public static final String VERSION = "1.0.0";

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
                .paths(PathSelectors.any()) // 可以根據url路徑設置哪些請求加入文檔,忽略哪些請求
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("swagger測試") //設置文檔的標題
                .description("swagger測試 API 接口文檔") // 設置文檔的描述
                .version(VERSION) // 設置文檔的版本信息
                .termsOfServiceUrl("http://www.csdn.net") //條款地址
                .license("The Apache License")//設置文檔的License信息
                .build();
    }
}

 

3、編寫API測試接口

@Api("用戶接口")
@RestController
public class UserController {

    @Resource
    private UserService userService;

    @ApiOperation(value = "通過用戶名查詢用戶信息", notes = "通過用戶名查詢用戶信息", produces = "application/json")
    @ApiImplicitParam(name = "name", value = "用戶名", paramType = "query", required = true, dataType = "String")
    @RequestMapping(value = "user/name", method = {RequestMethod.GET, RequestMethod.POST})
    public User getUser(String name) {
        User user = userService.selectUserByName(name);
        return user;
    }

    @ApiOperation(value = "通過用戶ID查詢用戶信息", notes = "通過用戶ID查詢用戶信息", produces = "application/json")
    @ApiImplicitParam(name = "id", value = "用戶ID", paramType = "query", required = true, dataType = "int", example="0")
    @RequestMapping(value = "user/id", method = {RequestMethod.GET, RequestMethod.POST})
    public User getUser(Integer id) {
        User user = userService.selectUserById(id);
        return user;
    }

    @ApiOperation(value = "通過用戶年齡查詢用戶信息", notes = "通過用戶年齡查詢用戶信息", produces = "application/json")
    @ApiImplicitParam(name = "age", value = "用戶年齡", paramType = "query", required = true, dataType = "int", example="0")
    @RequestMapping(value = "user/age", method = {RequestMethod.GET, RequestMethod.POST})
    public List<User> getUserByAge(Integer age) {
        PageHelper.startPage(1, 2);
        List<User> users = userService.selectUserByAge(age);
        return users;
    }

    @ApiOperation(value = "新增用戶", notes = "新增用戶", produces = "application/json")
    @ApiImplicitParams({@ApiImplicitParam(name = "name", value = "用戶名", paramType = "query", required = true, dataType = "String")
            , @ApiImplicitParam(name = "age", value = "用戶年齡", paramType = "query", required = true, dataType = "int", example="0")})
    @RequestMapping(value = "user/add", method = RequestMethod.POST)
    public User addUser(String name, Integer age) {
        User user = new User();
        user.setName(name);
        user.setAge(age);
        userService.insertUser(user);
        return user;
    }

    @ApiIgnore // 忽略這個API
    @ApiOperation(value = "批量新增用戶", notes = "批量新增用戶", produces = "application/json")
    @RequestMapping(value = "user/add/batch", method = RequestMethod.POST)
    public List<User> addUsers(@RequestBody List<User> users) {
        userService.batchInsertUser(users);
        return users;
    }

}

 

如果傳入的參數是對象,需要在對象的屬性上加@ApiModelProperty註解

import io.swagger.annotations.ApiModelProperty;

public class User {

	@ApiModelProperty("用戶ID")
	private Integer id;

	@ApiModelProperty("用戶名")
	private String name;

	@ApiModelProperty("用戶年齡")
	private Integer age;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

}

 

Swagger 通過註解定製接口對外展示的信息,這些信息包括接口名、請求方法、參數、返回信息等。

註解如下:

* @Api:修飾整個類,描述Controller的作用
* @ApiOperation:描述一個類的一個方法,或者說一個接口
* @ApiParam:單個參數描述
* @ApiModel:用對象來接收參數
* @ApiProperty:用對象接收參數時,描述對象的一個字段
* @ApiResponse:HTTP響應其中1個描述
* @ApiResponses:HTTP響應整體描述
* @ApiIgnore:使用該註解忽略這個API
* @ApiError :發生錯誤返回的信息
* @ApiImplicitParam:描述一個請求參數,可以配置參數的中文含義,還可以給參數設置默認值
* @ApiImplicitParams:描述由多個 @ApiImplicitParam 註解的參數組成的請求參數列表

 

4、啓動Springboot應用

啓動成功後,訪問 http://localhost:8080/swagger-ui.html,如圖所示:

 

5、測試接口

點擊其中一個接口進行測試:

點擊Try it out按鈕:

Execute 執行後,返回接口執行結果:

 

 

發佈了64 篇原創文章 · 獲贊 28 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章