SpringBoot框架整合SwaggerUI的示例代碼

整合swagger進行模塊測試

註意事項:為方便SpringBoot更好的整合Swagger,需要專門放置在一個模塊中(maven子工程)

創建公共模塊,整合swagger,為瞭所有模塊進行使用

common/pom.xml,導入相關的依賴

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <scope>provided </scope>
    </dependency>

    <!--mybatis-plus-->
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
    <!--lombok用來簡化實體類:需要安裝lombok插件-->
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    <!--swagger-->
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <artifactId>springfox-swagger-ui</artifactId>
    <!-- redis -->
        <artifactId>spring-boot-starter-data-redis</artifactId>
    <!-- spring2.X集成redis所需common-pool2
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
        <version>2.6.0</version>
    </dependency>-->
</dependencies>

在公共模塊下在創建一個模塊,如service_base

在該模塊下創建配置類(需要遵循SpringBoot規范,該代碼固定)

package com.xsha.servicebase;

import com.google.common.base.Predicates;
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.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 SwaggerConfig {
    @Bean
    public Docket webApiConfig(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("webApi")
                .apiInfo(webApiInfo())
                .select()
                .paths(Predicates.not(PathSelectors.regex("/admin/.*")))
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build();
    }
    private ApiInfo webApiInfo(){
        return new ApiInfoBuilder()
                .title("網站標題")
                .description("接口文檔的描述信息")
                .version("1.0")
                .contact(new Contact("java", "http://www.baidu.com", "[email protected]"))
}

使用方式

在其他模塊(最好是最外層的)的pom.xml引入上面的模塊即可

<dependency>
    <groupId>com.xsha</groupId>
    <artifactId>service_base</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

在該模塊的啟動類上添加ComponentScan註解,指定需要掃描的包。例如:@ComponentScan(basePackages={"com.xsha"})

然後啟動,訪問地址:http://127.0.0.1:8001/swagger-ui.html

統一返回結果的格式(自定義結果)

在公共模塊下在創建一個模塊,如common-utils

創建一個專門管理狀態碼的接口

public interface ResultCode {
    //定義兩個狀態碼
    public static int SUCCESS = 20000;
    public static int ERROR = 40000;
}

定義返回格式(較為固定)

package com.xsha.commonutils;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
// 統一返回結果類
@Data
public class R {
    @ApiModelProperty(value = "是否成功")
    private Boolean success;
    @ApiModelProperty(value = "返回碼")
    private Integer code;
    @ApiModelProperty(value = "返回消息")
    private String message;
    @ApiModelProperty(value = "返回數據")
    private Map<String, Object> data = new HashMap<String, Object>();
    // 把構造方法定為私有
    private R() {}
    // 成功靜態方法
    public static R ok() {
        R r = new R();
        r.setSuccess(true);
        r.setCode(ResultCode.SUCCESS);
        r.setMessage("成功");
        return r;
    }
    // 失敗靜態方法
    public static R error() {
        r.setSuccess(false);
        r.setCode(ResultCode.ERROR);
        r.setMessage("失敗");
    public R success(Boolean success){
        this.setSuccess(success);
        return this;
    public R message(String message){
        this.setMessage(message);
    public R code(Integer code){
        this.setCode(code);
    public R data(String key, Object value){
        this.data.put(key, value);
    public R data(Map<String, Object> map){
        this.setData(map);
}

使用方式

在其他模塊(最好是最外層的)的pom.xml引入上面的模塊即可

<dependency>
    <groupId>com.xsha</groupId>
    <artifactId>common_utils</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

每次返回的結果的類型必須是自定義的“返回格式”類類型

// please use rest style
// 1.select all teachers data
@ApiOperation(value = "所有數據列表")
@GetMapping("findAll")
public R findAllTeachers() {
    List<EduTeacher> teachers = teacherService.list(null);
    return R.ok().data("results", teachers);
}
// request path mast have variable id
// 2.logically delete teacher
@ApiOperation(value = "邏輯刪除數據")
@DeleteMapping("{id}")
public R logicDeleteTeacher(@ApiParam(name="id", value="講師ID", required = true) @PathVariable String id) {
    boolean flag = teacherService.removeById(id);
    return flag? R.ok(): R.error();
}

最後在swagger中測試即可

到此這篇關於SpringBoot框架整合SwaggerUI的文章就介紹到這瞭,更多相關SpringBoot整合SwaggerUI內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: