2
头图
The Swagger library provided by SpringFox has been used in the SpringBoot project before. I went to the official website and found that there has been no new version for nearly two years! A few days ago, upgraded the SpringBoot 2.6.x version, and found that the compatibility of this library is getting worse and worse. Some common annotation attributes have been abandoned and no replacement is provided! Accidentally found another Swagger library SpringDoc , tried it out very well, recommend it to everyone!

SpringBoot actual e-commerce project mall (50k+star) address: https://github.com/macrozheng/mall

Introduction to SpringDoc

SpringDoc is an API document generation tool that can be used in conjunction with SpringBoot. It is based on OpenAPI 3 and currently has 1.7K+Star on Github. It is quite diligent to update and release the version, and it is a better Swagger library! It is worth mentioning that SpringDoc not only supports Spring WebMvc projects, but also Spring WebFlux projects, and even Spring Rest and Spring Native projects. In short, it is very powerful. The following is an architecture diagram of SpringDoc.

use

Next, we will introduce the use of SpringDoc, using the mall-tiny-swagger project that integrated SpringFox before, I will transform it to use SpringDoc.

integrated

First, we have to integrate SpringDoc and add its dependencies in pom.xml . It works out of the box without any configuration.
<!--springdoc 官方Starter-->
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.6.6</version>
</dependency>

Migrating from SpringFox

  • Let's first take a look at the frequently used Swagger annotations and see what is the difference between SpringFox and SpringDoc. After all, we can quickly master new technologies by comparing the technologies we have learned;
SpringFoxSpringDoc
@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")
  • Next, we will transform the annotations used in the previous Controller, and compare the above table. The description attribute, which was abandoned in the @Api annotation for a long time and has not been replaced, is finally supported!
/**
 * 品牌管理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));
    }
}
  • Next, configure SpringDoc, use OpenAPI to configure basic document information, and configure grouped API documents through GroupedOpenApi SpringDoc supports configuration directly using the interface path.
/**
 * 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();
    }
}

Use with SpringSecurity

  • Since our project integrates SpringSecurity, it needs to be accessed through the JWT authentication header. We also need to configure the whitelist path of SpringDoc, mainly the resource path of 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();
        
    }

}
  • Then use the addSecurityItem method and the OpenAPI object in the SecurityScheme object to enable the JWT-based authentication function.
/**
 * 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")));
    }
}

test

  • We first log in through the login interface, and we can find that this version of Swagger returns results that support highlighting, and the version is obviously newer than SpringFox;

  • Then enter the obtained authentication header information through the authentication button. Note that there is no need to add the bearer prefix here;

  • After that, we can happily access the interface that requires login authentication;

  • Take a look at the documentation for request parameters, the familiar Swagger style!

Common configuration

SpringDoc also has some common configurations that you can learn about. For more configurations, you can refer to the official documentation.

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/**

Summarize

In the case that SpringFox's Swagger library has not been released for a long time, migrating to SpringDoc is indeed a better choice. I experienced a SpringDoc today. It is really easy to use. It is similar to the familiar usage before, and the learning cost is extremely low. Moreover, SpringDoc can support projects such as WebFlux, and its functions are more powerful. Friends who are a little stuck with SpringFox can migrate to it and try!

If you want to learn more SpringBoot combat skills, you can try this practical project with a full set of tutorials (50K+Star): https://github.com/macrozheng/mall

References

Project source code address

https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-springdoc


macrozheng
1.1k 声望1.3k 粉丝