SpringBoot整合Knife4j实现接口文档

1. 引入依赖

<parent>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-parentartifactId>
    <version>2.6.11version>
    <relativePath/> 
parent>

<dependencies>
    <dependency>
        <groupId>com.github.xiaoymingroupId>
        <artifactId>knife4j-spring-boot-starterartifactId>
        <version>3.0.3version>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
        <optional>trueoptional>
    dependency>

dependencies>

2. 编写配置类

@ConfigurationProperties(prefix = "swagger.doc")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SwaggerProperties {

    private boolean enable = true;

    /**
     * 作者
     */
    private String author;

    /**
     * 标题
     */
    private String title;

    /**
     * 项目描述
     */
    private String description;

    /**
     * 官网地址
     */
    private String url;

    /**
     * 邮箱地址
     */
    private String email;
}

3. 编写配置类配置knife4j

@ConditionalOnClass(EnableSwagger2.class)
@Configuration
@EnableSwagger2
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)
@EnableConfigurationProperties(SwaggerProperties.class)
public class Knife4jConfiguration implements WebMvcConfigurer {

    @Autowired
    private SwaggerProperties swaggerProperties;

    @Autowired
    private ApplicationInfo applicationInfo;


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

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

                //spring boot 2.6以上版本使用 PATH_PATTERN_PARSER,swagger并没有兼容,所以替换为 ANT_PATH_MATCHER
                if(bean instanceof WebMvcProperties){
                    WebMvcProperties pathmatch = (WebMvcProperties)bean;
                    pathmatch.getPathmatch().setMatchingStrategy(WebMvcProperties.MatchingStrategy.ANT_PATH_MATCHER);
                }

                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);
                }
            }
        };
    }


    @Bean
    public Docket createRestApi() {
        Docket docket = new Docket(DocumentationType.OAS_30).pathMapping("/")
                .groupName(SpringUtil.getApplicationName())
                // 定义是否开启swagger,false为关闭,可以通过变量控制
                .enable(true)
                // 将api的元信息设置为包含在json ResourceListing响应中。
                .apiInfo(apiInfo())
                // 选择哪些接口作为swagger的doc发布
                .select()
                //指定某个路径才能生成swagger
                .paths(PathSelectors.any())
                .paths(s -> !PathSelectors.regex("/error/*").test(s))
                .build()
                //是否启用
                .enable(swaggerProperties.isEnable())
                // 支持的通讯协议集合
                .protocols(new HashSet<>(Arrays.asList("https", "http")));
        return docket;
    }

    /**
     * API 页面上半部分展示信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .contact(new Contact(swaggerProperties.getAuthor(), swaggerProperties.getUrl(), swaggerProperties.getEmail()))
                .version(applicationInfo.getVersion())
                .build();
    }
}

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