springboot集成swager-ui2.0

本文介绍了如何在SpringBoot2.6版本中使用Swagger进行API文档生成,包括在pom.xml中添加依赖,配置Swagger和Knife4j,解决与SpringMVC的兼容问题,以及WebMvcConfig中的资源处理设置。
摘要由CSDN通过智能技术生成

1、pom文件添加依赖

        <!-- swagger-ui -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>3.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-ui</artifactId>
            <version>3.0.2</version>
        </dependency>

2、添加配置文件

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.annotation.Nonnull;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类 名 称:SwaggerConfig
 * 类 描 述:Swagger配置
 * 创建时间:2024/4/3 10:11
 * 创 建 人:ZZP
 */
@EnableSwagger2
@EnableKnife4j
/**
 * Spring Boot 2.6 与 swagger 不兼容解决
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(WebMvcRequestHandlerProvider.class)
public class SwaggerConfig {
    @Value("${chenxi.swagger.enable:false}")
    private Boolean swaggerEnable;

    /**
     * Spring Boot 2.6 与 swagger 不兼容解决
     */
    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {

            @Override
            public Object postProcessAfterInitialization(@Nonnull Object bean, @Nonnull 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);
                }
            }
        };
    }

    @Bean(value = "defaultApi2")
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swaggerEnable)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.*.*.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("数据质量服务")
                .contact(new Contact("颜人中", "/doc.html", "honglei_chen@dnt.com.cn"))
                .description("***接口,是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。")
                .version("1.0")
                .build();
    }
}

3、WebMvcConfig放行

@Configuration
@EnableWebMvc
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

4、访问地址:ip:端口/doc.html

Spring Boot项目中集成Swagger UI非常简单。以下是一些基本的步骤: 1. 添加Swagger依赖:在项目的`pom.xml`文件中添加Swagger的相关依赖。可以使用以下依赖: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` 2. 创建Swagger配置类:创建一个Java类,用于配置Swagger。可以使用以下示例代码: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket apiDocket() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API Documentation") .description("API Documentation for My Awesome App") .version("1.0.0") .build(); } } ``` 在上述代码中,`@EnableSwagger2`注解启用Swagger,`@Bean`注解创建一个`Docket`实例,配置Swagger的基本信息和扫描的包路径。 3. 启动应用程序:运行Spring Boot应用程序,Swagger UI将在`http://localhost:8080/swagger-ui.html`上自动启动。 现在,您可以在Swagger UI中浏览和测试您的API。Swagger UI将根据您的代码和注释生成API文档,并提供一个交互式的界面,供用户查看和测试API的各个端点和参数。 请注意,上述示例代码中的包路径和其他配置可能需要根据您的项目结构进行调整。此外,还可以通过其他配置选项来自定义Swagger UI的行为和外观。更多详细信息,请参阅Swagger和Springfox的官方文档。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值