SpringBoot 2.6 集成 swagger 3.0

高版本SpringBoot集成swagger 3.0

为了方便在线测试API,相信很多项目都没有弃用swagger,swagger依然是在线文档生成优秀框架。如今swagger也迭代到3.0,整体ui风格相比较swagger2更加整洁,配置方面也调整了不少,非常容易踩坑~

1、引入依赖坐标

 
 <dependency>
     <groupId>io.springfoxgroupId>
     <artifactId>springfox-boot-starterartifactId>
     <version>3.0.0version>
 dependency>

2、主程序添加@EnableOpenApi注解,这是swagger 3.0新增的注解

@EnableOpenApi
@SpringBootApplication
public class WxStubApplication {
    public static void main(String[] args) {
        SpringApplication.run(WxStubApplication.class, args);
    }
}

3、修改SpringMVC默认路径匹配策略(因为Springfox使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher

# swagger3
spring.mvc.pathmatch.matching-strategy=ant_path_matcher

4、编写配置类,配置swagger

/**
 * @description:
 * @author: laizhenghua
 * @date: 2022/8/30 20:32
 */
@Configuration
public class SwaggerConfiguration {
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.OAS_30)
                .select().apis(RequestHandlerSelectors.basePackage("com.laizhenghua.wxstub.controller"))
                .paths(PathSelectors.any()).build()
                .apiInfo(setApiInfo());
    }
    private ApiInfo setApiInfo() {
        Contact contact = new Contact("laizhenghua", "https://blog.csdn.net/m0_46357847", "[email protected]");
        ApiInfo info = new ApiInfo("微信消息推送助手", "每天定时推送微信消息", "v1.0",
                "https://blog.csdn.net/m0_46357847", contact, "Apache 2.0", "", new ArrayList<VendorExtension>());
        return info;
    }

    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }
}

5、使用swagger 3.0方式也是和2.0一样,只需在类、方法、参数上添加相应的注解即可

/**
 * @description: PushController
 * @author: laizhenghua
 * @date: 2022/8/30 12:39
 */
@Api(tags = "APP-微信消息推送助手")
@RestController
@RequestMapping(RestURL.PUSH_URL)
public class PushController {

    @Autowired
    private PushService pushService;

    @ApiOperation(value = "推送:每天定时推送微信消息", notes = "api/push/message", response = R.class)
    @RequestMapping(value = "/message", method = RequestMethod.GET)
    public R pushMessage(@ApiParam(value = "微信号", required = true) String wxId) {
        return R.ok().put("data", pushService.pushMessage());
    }
}

6、效果图(访问http://127.0.0.1:8080/swagger-ui/index.html

SpringBoot 2.6 集成 swagger 3.0_第1张图片

你可能感兴趣的:(JavaEE,spring,boot,java,spring)