之前在SpringBoot專案中一直使用的是SpringFox提供的Swagger庫,上了下官網發現已經有接近兩年沒出新版本了!前幾天升級了SpringBoot 2.6.x 版本,發現這個庫的相容性也越來越不好了,有的常用註解屬性被廢棄了居然都沒提供替代!無意中發現了另一款Swagger庫SpringDoc
,試用了一下非常不錯,推薦給大家!
SpringBoot實戰電商專案mall(50k+star)地址:https://github.com/macrozheng/mall
SpringDoc簡介
SpringDoc是一款可以結合SpringBoot使用的API文件生成工具,基於OpenAPI 3
,目前在Github上已有1.7K+Star
,更新發版還是挺勤快的,是一款更好用的Swagger庫!值得一提的是SpringDoc不僅支援Spring WebMvc專案,還可以支援Spring WebFlux專案,甚至Spring Rest和Spring Native專案,總之非常強大,下面是一張SpringDoc的架構圖。
使用
接下來我們介紹下SpringDoc的使用,使用的是之前整合SpringFox的mall-tiny-swagger
專案,我將把它改造成使用SpringDoc。
整合
首先我們得整合SpringDoc,在pom.xml
中新增它的依賴即可,開箱即用,無需任何配置。
<!--springdoc 官方Starter-->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.6</version>
</dependency>
從SpringFox遷移
- 我們先來看下經常使用的Swagger註解,看看SpringFox的和SpringDoc的有啥區別,畢竟對比已學過的技術能該快掌握新技術;
SpringFox | SpringDoc |
---|---|
@Api | @Tag |
@ApiIgnore | @Parameter(hidden = true) or @Operation(hidden = true) or @Hidden |
@ApiImplicitParam | @Parameter |
@ApiImplicitParams | @Parameters |
@ApiModel | @Schema |
@ApiModelProperty | @Schema |
@ApiOperation(value = "foo", notes = "bar") | @Operation(summary = "foo", description = "bar") |
@ApiParam | @Parameter |
@ApiResponse(code = 404, message = "foo") | ApiResponse(responseCode = "404", description = "foo") |
- 接下來我們對之前Controller中使用的註解進行改造,對照上表即可,之前在
@Api
註解中被廢棄了好久又沒有替代的description
屬性終於被支援了!
/**
* 品牌管理Controller
* Created by macro on 2019/4/19.
*/
@Tag(name = "PmsBrandController", description = "商品品牌管理")
@Controller
@RequestMapping("/brand")
public class PmsBrandController {
@Autowired
private PmsBrandService brandService;
private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);
@Operation(summary = "獲取所有品牌列表",description = "需要登入後訪問")
@RequestMapping(value = "listAll", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<PmsBrand>> getBrandList() {
return CommonResult.success(brandService.listAllBrand());
}
@Operation(summary = "新增品牌")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
@PreAuthorize("hasRole('ADMIN')")
public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {
CommonResult commonResult;
int count = brandService.createBrand(pmsBrand);
if (count == 1) {
commonResult = CommonResult.success(pmsBrand);
LOGGER.debug("createBrand success:{}", pmsBrand);
} else {
commonResult = CommonResult.failed("操作失敗");
LOGGER.debug("createBrand failed:{}", pmsBrand);
}
return commonResult;
}
@Operation(summary = "更新指定id品牌資訊")
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
@PreAuthorize("hasRole('ADMIN')")
public CommonResult updateBrand(@PathVariable("id") Long id, @RequestBody PmsBrand pmsBrandDto, BindingResult result) {
CommonResult commonResult;
int count = brandService.updateBrand(id, pmsBrandDto);
if (count == 1) {
commonResult = CommonResult.success(pmsBrandDto);
LOGGER.debug("updateBrand success:{}", pmsBrandDto);
} else {
commonResult = CommonResult.failed("操作失敗");
LOGGER.debug("updateBrand failed:{}", pmsBrandDto);
}
return commonResult;
}
@Operation(summary = "刪除指定id的品牌")
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasRole('ADMIN')")
public CommonResult deleteBrand(@PathVariable("id") Long id) {
int count = brandService.deleteBrand(id);
if (count == 1) {
LOGGER.debug("deleteBrand success :id={}", id);
return CommonResult.success(null);
} else {
LOGGER.debug("deleteBrand failed :id={}", id);
return CommonResult.failed("操作失敗");
}
}
@Operation(summary = "分頁查詢品牌列表")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasRole('ADMIN')")
public CommonResult<CommonPage<PmsBrand>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1")
@Parameter(description = "頁碼") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "3")
@Parameter(description = "每頁數量") Integer pageSize) {
List<PmsBrand> brandList = brandService.listBrand(pageNum, pageSize);
return CommonResult.success(CommonPage.restPage(brandList));
}
@Operation(summary = "獲取指定id的品牌詳情")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasRole('ADMIN')")
public CommonResult<PmsBrand> brand(@PathVariable("id") Long id) {
return CommonResult.success(brandService.getBrand(id));
}
}
- 接下來進行SpringDoc的配置,使用
OpenAPI
來配置基礎的文件資訊,通過GroupedOpenApi
配置分組的API文件,SpringDoc支援直接使用介面路徑進行配置。
/**
* SpringDoc API文件相關配置
* Created by macro on 2022/3/4.
*/
@Configuration
public class SpringDocConfig {
@Bean
public OpenAPI mallTinyOpenAPI() {
return new OpenAPI()
.info(new Info().title("Mall-Tiny API")
.description("SpringDoc API 演示")
.version("v1.0.0")
.license(new License().name("Apache 2.0").url("https://github.com/macrozheng/mall-learning")))
.externalDocs(new ExternalDocumentation()
.description("SpringBoot實戰電商專案mall(50K+Star)全套文件")
.url("http://www.macrozheng.com"));
}
@Bean
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group("brand")
.pathsToMatch("/brand/**")
.build();
}
@Bean
public GroupedOpenApi adminApi() {
return GroupedOpenApi.builder()
.group("admin")
.pathsToMatch("/admin/**")
.build();
}
}
結合SpringSecurity使用
- 由於我們的專案整合了SpringSecurity,需要通過JWT認證頭進行訪問,我們還需配置好SpringDoc的白名單路徑,主要是Swagger的資源路徑;
/**
* SpringSecurity的配置
* Created by macro on 2018/4/26.
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf()// 由於使用的是JWT,我們這裡不需要csrf
.disable()
.sessionManagement()// 基於token,所以不需要session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, // Swagger的資源路徑需要允許訪問
"/",
"/swagger-ui.html",
"/swagger-ui/",
"/*.html",
"/favicon.ico",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/swagger-resources/**",
"/v3/api-docs/**"
)
.permitAll()
.antMatchers("/admin/login")// 對登入註冊要允許匿名訪問
.permitAll()
.antMatchers(HttpMethod.OPTIONS)//跨域請求會先進行一次options請求
.permitAll()
.anyRequest()// 除上面外的所有請求全部需要鑑權認證
.authenticated();
}
}
- 然後在
OpenAPI
物件中通過addSecurityItem
方法和SecurityScheme
物件,啟用基於JWT的認證功能。
/**
* SpringDoc API文件相關配置
* Created by macro on 2022/3/4.
*/
@Configuration
public class SpringDocConfig {
private static final String SECURITY_SCHEME_NAME = "BearerAuth";
@Bean
public OpenAPI mallTinyOpenAPI() {
return new OpenAPI()
.info(new Info().title("Mall-Tiny API")
.description("SpringDoc API 演示")
.version("v1.0.0")
.license(new License().name("Apache 2.0").url("https://github.com/macrozheng/mall-learning")))
.externalDocs(new ExternalDocumentation()
.description("SpringBoot實戰電商專案mall(50K+Star)全套文件")
.url("http://www.macrozheng.com"))
.addSecurityItem(new SecurityRequirement().addList(SECURITY_SCHEME_NAME))
.components(new Components()
.addSecuritySchemes(SECURITY_SCHEME_NAME,
new SecurityScheme()
.name(SECURITY_SCHEME_NAME)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")));
}
}
測試
- 接下來啟動專案就可以訪問Swagger介面了,訪問地址:http://localhost:8088/swagger...
- 我們先通過登入介面進行登入,可以發現這個版本的Swagger返回結果是支援高亮顯示的,版本明顯比SpringFox來的新;
- 然後通過認證按鈕輸入獲取到的認證頭資訊,注意這裡不用加
bearer
字首;
- 之後我們就可以愉快地訪問需要登入認證的介面了;
- 看一眼請求引數的文件說明,還是熟悉的Swagger樣式!
常用配置
SpringDoc還有一些常用的配置可以瞭解下,更多配置可以參考官方文件。
springdoc:
swagger-ui:
# 修改Swagger UI路徑
path: /swagger-ui.html
# 開啟Swagger UI介面
enabled: true
api-docs:
# 修改api-docs路徑
path: /v3/api-docs
# 開啟api-docs
enabled: true
# 配置需要生成介面文件的掃描包
packages-to-scan: com.macro.mall.tiny.controller
# 配置需要生成介面文件的介面路徑
paths-to-match: /brand/**,/admin/**
總結
在SpringFox的Swagger庫好久不出新版的情況下,遷移到SpringDoc確實是一個更好的選擇。今天體驗了一把SpringDoc,確實很好用,和之前熟悉的用法差不多,學習成本極低。而且SpringDoc能支援WebFlux之類的專案,功能也更加強大,使用SpringFox有點卡手的朋友可以遷移到它試試!
如果你想了解更多SpringBoot實戰技巧的話,可以試試這個帶全套教程的實戰專案(50K+Star):https://github.com/macrozheng/mall