先貼效果
image.png
- 右上角可以選擇分組,每個(gè)分組下可以設(shè)標(biāo)簽管理api
- 每個(gè)api可以直接測(cè)試
1. maven dependency
新建maven項(xiàng)目,這里使用的是idea的Spring Initializr,勾選web依賴,就快速構(gòu)建了SpringBoot項(xiàng)目,有了tomcat和發(fā)布RESTful API能力指厌。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
2. 配置swagger2
主要是構(gòu)建Docket Bean,SwaggerConfig.java代碼如下:
@Configuration
@EnableSwagger2
@Profile({"dev", "test"})
public class SwaggerConfig {
@Bean
public Docket apiGroup1() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("Group 1").tags(
new Tag("標(biāo)簽一", "描述")
, new Tag("標(biāo)簽二", "描述")
)
.apiInfo(this.getApiInfo("接口", "接口"))
.select()
.apis(RequestHandlerSelectors.any())
.paths(or(regex("/demo.*")))
.build();
}
private ApiInfo getApiInfo(String title, String desc) {
return new ApiInfo(
"XX系統(tǒng) " + title + " API",
desc + " API文檔",
"1.0",
"",
new Contact("聯(lián)系我們", "", "mail@mail.com"),
"license",
"licenseUrl",
new ArrayList<>());
}
- @Profile({"dev", "test"}) 指明了只在dev和test profile運(yùn)行時(shí)啟用swagger踊跟,如實(shí)際項(xiàng)目運(yùn)行prod profile時(shí)就不啟用swagger
- .groupName可以不設(shè)踩验,默認(rèn)會(huì)有一個(gè)default的分組,實(shí)際項(xiàng)目中模塊比較多商玫,這個(gè)分組會(huì)比較實(shí)用晰甚,UI中右上角可以切換分組。 分組可以把多個(gè)tag組織在一起决帖,通常是一個(gè)controler對(duì)應(yīng)一個(gè)tag。需要加一個(gè)分組可以再建一個(gè)Docket Bean蓖捶。
3. 新增Controller
package com.bq.demo.test;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.User;
import org.springframework.web.bind.annotation.*;
@Api(value = "/demo/test", tags = "標(biāo)簽一")
@RestController
@RequestMapping("/demo/test")
public class TestSwaggerController {
@ApiOperation(value = "顯示helloWorld", notes = "顯示helloWorld")
@GetMapping("/helloWorld")
public Object showInfo() {
return "hello world";
}
@ApiOperation(value = "添加用戶信息", notes = "添加用戶信息")
@ApiImplicitParam(name = "user", value = "User", required = true, dataType = "User")
@PostMapping("/addUser")
public Object addUser(@RequestBody User user) {
return "success";
}
}
- 注意@Api中tags和上面group中的對(duì)應(yīng)
- 標(biāo)簽二的Controller代碼只是復(fù)制了一份地回,改了下@Api和@RequestMapping映射
- 打開 http://localhost:8080/swagger-ui.html 測(cè)試