Spring Boot整合Swagger2的流程

  • 由于springboot的便捷,以及前后端分離的趨勢,后端和前端配合的橋梁便是接口細節(jié),我們通常遵守REST的原則,為其他開發(fā)人員提供一份REST接口文檔,但后期接口多又雜,手寫十分耗時耗力。因此出現(xiàn)了Swagegr2

Swagger2,

它可以輕松的整合到Spring Boot中,并與Spring MVC程序配合組織出強大RESTful API文檔。它既可以減少我們創(chuàng)建文檔的工作量,同時說明內(nèi)容又整合入實現(xiàn)代碼中,讓維護文檔和修改代碼整合為一體,可以讓我們在修改代碼邏輯的同時方便的修改文檔說明。

Swagger2官方文檔


maven引入Swagger2依賴

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

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

創(chuàng)建一個swagger2的配置類

image
@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("系統(tǒng)Restful API")
                .description("系統(tǒng)Restful API描述")
                .contact(new Contact("測試", "xxx", "sss"))
                .version("1.0")
                .build();
    }
    private ApiInfo apiInfo() {
    return new ApiInfo(
      "My REST API", 
      "Some custom description of API.", 
      "API TOS", 
      "Terms of service", 
      new Contact("John Doe", "www.example.com", "myeaddress@company.com"), 
      "License of API", "API license URL", Collections.emptyList());
}
}

  • 兩種apiInfo()寫法都可以

如上代碼所示,通過@Configuration注解,讓Spring來加載該類配置。再通過@EnableSwagger2注解來啟用Swagger2。apiInfo()返回了關于接口界面的自定義信息。例如郵件,協(xié)議信息--Apache 2.0。

添加每個接口的詳細信息

  • 我們通過@ApiOperation注解來給API增加說明、通過@ApiImplicitParams、@ApiImplicitParam注解來給參數(shù)增加說明。
@RestController
@RequestMapping(value="/users")     // 通過這里配置使下面的映射都在/users下,可去除
public class UserController {

    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());

    @ApiOperation(value="獲取用戶列表", notes="")
    @RequestMapping(value={""}, method=RequestMethod.GET)
    public List<User> getUserList() {
        List<User> r = new ArrayList<User>(users.values());
        return r;
    }

    @ApiOperation(value="創(chuàng)建用戶", notes="根據(jù)User對象創(chuàng)建用戶")
    @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
    @RequestMapping(value="", method=RequestMethod.POST)
    public String postUser(@RequestBody User user) {
        users.put(user.getId(), user);
        return "success";
    }

    @ApiOperation(value="獲取用戶詳細信息", notes="根據(jù)url的id來獲取用戶詳細信息")
    @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long")
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

    @ApiOperation(value="更新用戶詳細信息", notes="根據(jù)url的id來指定更新對象,并根據(jù)傳過來的user信息來更新用戶詳細信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
    })
    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    public String putUser(@PathVariable Long id, @RequestBody User user) {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    @ApiOperation(value="刪除用戶", notes="根據(jù)url的id來指定刪除對象")
    @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long")
    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }

}

這時啟動springboot,訪問http://localhost:8080/your-app-root/swagger-ui.html

demo有些簡單,希望大神輕噴

image

關于Swagger2 ,是一個十分優(yōu)秀的插件,極大的提高了工作效率。本人才疏學淺,對于Swagger2的了解也比不上各位高手掌握的程度,但人生,就是一個不斷學習的過程。

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容