天天看點

【swagger2】SpringBoot內建springfox-swagger2建構restful APIspringboot整合swagger2參考文章

springboot整合swagger2

文章 SpringMVC內建springfox-swagger2建構restful API 簡單寫了如何在springmvc中內建swagger2。這邊記錄下在springboot中如何內建swagger2,其實使用基本相同。

一、引入依賴

使用maven,在pom.xml中引用相關依賴(swagger版本2.4.0,springboot的版本為2.1.5.RELEASE):

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

二、建立swagger的配置類

這個配置類和springmvc的寫法完全一緻。

package com.xingguo.springboot;

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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2Configuration {

    @Bean
    public Docket buildDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(buildApiInf())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xingguo.springboot.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo buildApiInf(){
        return new ApiInfoBuilder()
                    .title("xingguo大标題")
                    .description("springboot swagger2")
                    .termsOfServiceUrl("http://blog.csdn.net/u014231523網址連結")
                    .contact(new Contact("diaoxingguo", "http://blog.csdn.net/u014231523", "[email protected]"))
                    .build();

    }

}
           

其中,除了RequestHandlerSelectors.basePackage(xxx)需要修改外,其他配置都不需要改變。

在原來2.2.0的版本中使用new ApiInfo()的方法已經過時,使用new ApiInfoBuilder()進行構造,需要什麼參數就添加什麼參數。當然也可以什麼都添加。如:

private ApiInfo buildApiInfo(){
    return new ApiInfoBuilder().build();
}
           

三、在controller添加相關的注解

常用的注解如下:

- @Api()用于類名

- @ApiOperation()用于方法名

- @ApiParam()用于參數說明

- @ApiModel()用于實體類

- @ApiModelProperty用于實體類屬性

更加詳細的含義可以參考 官方說明wiki ,下面會用代碼和示例圖說明。

四、啟動項目

在浏覽器上輸入url:http://{ip}:{port}/swagger-ui.html#/ ,url中不必輸入#/

在application.properties中設定端口号為9090(如果不設定,預設為8080)

server.port=9090
           

是以url是:http://localhost:9090/swagger-ui.html,如圖:

【swagger2】SpringBoot內建springfox-swagger2建構restful APIspringboot整合swagger2參考文章

這裡會把相應包下的所有controller按類(tag或@Api)進行顯示。

五、示例代碼

我們看下其中一個類UserController.java,(請忽略業務邏輯,隻看注解)

package com.xingguo.springboot.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.xingguo.springboot.model.User;
import com.xingguo.springboot.service.UserService;


@Api(value="使用者controller",description="使用者操作",tags={"使用者操作接口"})
@RestController
public class UserController {

    @Resource
    private UserService userService;

    @ApiOperation("擷取使用者資訊")
    @GetMapping("/getUserInfo")
    public User getUserInfo(@ApiParam(name="id",value="使用者id",required=true) Long id,@ApiParam(name="username",value="使用者名") String username) {
        User user = userService.getUserInfo();
        return user;
    }

    @ApiOperation("更改使用者資訊")
    @PostMapping("/updateUserInfo")
    public int updateUserInfo(@RequestBody @ApiParam(name="使用者對象",value="傳入json格式",required=true) User user){
        int num = userService.updateUserInfo(user);
        return num;
    }

    @ApiOperation("添加使用者資訊")
    @PostMapping("/saveUser")
    public String saveUser(@RequestBody @ApiParam(name="user",value="json fromat",required=true) User user) {
        userService.saveUser(user);
        return "success";
    }
}
           

這裡說明下,在使用對象作為參數時,可以在對象上添加相應的注解,使用者頁面顯示。如:

package com.xingguo.springboot.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.util.List;

@ApiModel(description="使用者對象user")
public class User {
    @ApiModelProperty(value="使用者名",name="username")
    private String username;
    @ApiModelProperty(value="狀态",name="state",required=true)
    private Integer state;
    private String password;
    private String nickName;
    private Integer isDeleted;

    private String[] ids;
    private List<String> idList;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String[] getIds() {
        return ids;
    }

    public void setIds(String[] ids) {
        this.ids = ids;
    }

    public List<String> getIdList() {
        return idList;
    }

    public void setIdList(List<String> idList) {
        this.idList = idList;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public Integer getIsDeleted() {
        return isDeleted;
    }

    public void setIsDeleted(Integer isDeleted) {
        this.isDeleted = isDeleted;
    }

}
           

顯示的效果如圖:

【swagger2】SpringBoot內建springfox-swagger2建構restful APIspringboot整合swagger2參考文章
【swagger2】SpringBoot內建springfox-swagger2建構restful APIspringboot整合swagger2參考文章

看上圖紅框的部分,其中一個是json格式的點選就可以擷取參數格式。

第二張中可以看到字段相應的注釋和是否必填。如果在字段上添加注釋@ApiModelProperty(required=true) 就是必填(預設是false),相應的頁面optional辨別也會消失,辨別這個字段必填。

點選下面的try it out按鈕就可以進行調試。

在使用單個參數時,如上面代碼中的getUserInfo()方法,對應的效果圖如下:

【swagger2】SpringBoot內建springfox-swagger2建構restful APIspringboot整合swagger2參考文章

這裡如果是添加required=true,@ApiParam(required=true)則會在頁面上顯示required的辨別。同樣預設為false。其他的使用方式可以自己動手試試。

參考文章

https://blog.csdn.net/u014231523/article/details/54562695

繼續閱讀