天天看點

Springboot 整合Swagger 2架構 讓接口檢視及調試更加優雅

先是pom.xml檔案添加依賴:

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

application.yml不需要做配置

接着是Swagger2的配置類  Swagger2Config.java:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
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;

/**
 * @Author:JCccc
 * @Description:
 * @Date: created in 20:50 2019/5/25
 */
@Configuration
@EnableSwagger2
public class Swagger2Config extends WebMvcConfigurationSupport {

    /**
     * 因為 Swagger2的資源檔案都是在jar包裡面,如果不在此處配置加載靜态資源,
     * 會導緻請求http://localhost:8081/swagger-ui.html失敗
     *  <!--swagger資源配置-->
     *  <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
     *  <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
     *
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.soelegant.elegantdemo.controller"))
                .paths(PathSelectors.any())
                .build()
                //不需要時,或者生産環境可以在此處關閉
                .enable(true);

    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("JCccc springboot整合Swagger2項目 ")
                .description("描述:測試使用Swagger2!")
                //服務條款網址
                .t
                .contact("JCccc")
                .version("1.0")
                .build();
    }



}      

 然後是寫一個Controller ,整合Swagger2架構注解 Swagger2TestController.java:

import com.alibaba.fastjson.JSONObject;
import com.soelegant.elegantdemo.pojo.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

/**
 * @Author:JCccc
 * @Description:
 * @Date: created in 20:54 2019/5/25
 */
@Api(value = "測試各種方法", tags = {"測試使用Controller"})
@RestController
public class Swagger2TestController {

    @ApiOperation(value = "測試Swagger2接口", notes = "傳入編号!")
    @ApiImplicitParam(name = "id", value = "id", required = true)
    @RequestMapping(value = "/swaTest2/{id}", method = RequestMethod.GET)
    public String TestSwa2(@PathVariable("id") Integer id) {
        System.out.println("swaTest!");
        //  Optional<UserInfo> user = userRepository.findById(id);
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername("test");
        userInfo.setState(1);
        userInfo.setPassword("123456");
        userInfo.setNickName("testNickName");
        userInfo.setIsDeleted(id);
        userInfo.setIds(null);
        userInfo.setIdList(null);
        return userInfo.toString();
    }


    @ApiOperation(value = "swaTest3", notes = "測試GET!")
    @ApiImplicitParam(name = "name", value = "使用者name")
    @RequestMapping(value = "/swaTest3", method = RequestMethod.GET)
    public String TestSwa3(@RequestParam("name") String name) {
        System.out.println("swaTest!");


        return name;
    }


    @ApiOperation(value = "swaTest4", notes = "測試POST!")
    @RequestMapping(value = "/swaTest4", method = RequestMethod.POST)
    public String TestSwa4(@RequestBody JSONObject jsonObject) {
        System.out.println("swaTest4!" + jsonObject.toString());

        String str = jsonObject.toString();
        return str;
    }



    @ApiOperation(value = "swaTest5", notes = "測試對象傳值!")
    @RequestMapping(value = "/swaTest5", method = RequestMethod.POST)
    public String TestSwa5(UserInfo userInfo) {

        return userInfo.toString();
    }

}      

可以看到上面的第一個接口用到了UserInfo實體類, 那麼我們也将這個跟接口有關的類也結合Swagger2注解  UserInfo.java:

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

import java.io.Serializable;
import java.util.List;

/**
 * @Author:JCccc
 * @Description:
 * @Date: created in 20:57 2019/5/25
 */
@Data
@ApiModel(value = "userInfo 對象",description = "使用者對象user")
public class UserInfo implements Serializable {
    private static final long serialVersionUID = 1L;
    @ApiModelProperty(value="使用者名",name="username",example="lx")
    private String username;
    @ApiModelProperty(value="狀态",name="state",required=true)
    private Integer state;
    private String password;
    private String nickName;
    private Integer isDeleted;

    @ApiModelProperty(value="id數組",hidden=true)
    private String[] ids;
    private List<String> idList;



}      

那麼到此,我們整合Swagger2基本已經完畢,接下來看看效果:

運作項目後,進入Swagger2的接口頁面:​​http://localhost:8099/swagger-ui.html#​​      (端口就是自己項目的端口,我自己的是8099)

Springboot 整合Swagger 2架構 讓接口檢視及調試更加優雅

 然後可以點開接口看看,順便還可以線上調試(點開接口,點選Try it out):

Springboot 整合Swagger 2架構 讓接口檢視及調試更加優雅

然後/swaTest4這個接口是通過@RequestBody JSONObject jsonObject 接收參數,是以在Swagger2的接口頁面上,我們也傳入一個json格式資料:

{
   "userName": "testName",
   "userId":"22222222"
 }      

如圖:

Springboot 整合Swagger 2架構 讓接口檢視及調試更加優雅

繼續閱讀