swagger 3.0.0 集成 springboot 2.6+ 生成doc.html 和swagger-ui

1.项目中引入pom.xml依赖

 <!-- 依赖版本管理 -->
    <properties>
        <swagger.version>3.0.0</swagger.version>
        <swagger-bootstrap-ui.version>3.0.3</swagger-bootstrap-ui.version>
    </properties>
     <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>

        <!--swagger-ui.html模式        -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <!-- Swagger 3 API接口调试工具        -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <!-- 引入knife4j-spring-ui包 /doc.html-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>${swagger-bootstrap-ui.version}</version>
        </dependency>

特别说明: doc.html模式 swagger-bootstrap-ui只支持Swagger 2 knife4j是swagger-bootstrap-ui的升级版,支持Swagger 3。

2.创建Swagger2Config配置类

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
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 java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Configuration
@EnableSwagger2
@Profile({"test"}) //在啥样的配置文件环境生效
public class Swagger2Config implements WebMvcConfigurer {

    /**
     * 显示swagger-ui文档展示页,还必须注入swagger资源:
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//      registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
     *
     * @return Docket
     */
    @Bean
    public Docket userSecurity() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //此包路径下的类,才生成接口文档
                .apis(RequestHandlerSelectors.basePackage("com.jinyi.up.security"))
                //加了ApiOperation注解的类,才生成接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .groupName("用户安全管理");
        //.globalOperationParameters(setHeaderToken());
    }

    /**
     * api文档的详细信息函数,注意这里的注解引用的是哪个     
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("XX项目")
                .description(" API 1.0 操作文档")
                .termsOfServiceUrl("")
                .version("1.0")
                .contact(new Contact("葵花宝典", "", "464945880@qq.com"))
                .build();
    }

    /**
     * 设置请求头
     *
     * @return
     */
    private List<Parameter> setRequestHeaders() {
        ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        ticketPar.name("X-Access-Token").description("用户token")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build(); //header中的ticket参数非必填,传空也可以
        pars.add(ticketPar.build());      //根据每个方法名也知道当前方法在设置什么参数
        return pars;
    }

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

3.启动类输出文档地址

@Slf4j
@SpringBootApplication
public class JinyiSecurityApplication {

    public static void main(String[] args) throws UnknownHostException {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(JinyiSecurityApplication.class, args);
        Environment env = applicationContext.getEnvironment();
        String ip = InetAddress.getLocalHost().getHostAddress();
        String port = env.getProperty("server.port");
//        String activePrn ofile = SpringContext.getActiveProfile();
        log.info("\n----------------------------------------------------------\n\t" +
                "Application is running! Access URLs:\n\t" +
                "Doc: \t\thttp://" + ip + ":" + port + "/doc.html\n\t" +
                "Swagger: \thttp://" + ip + ":" + port + "/swagger-ui/\n\t" +
                "----------------------------------------------------------");
    }
}

项目运行后 控制台输出log见下图
在这里插入图片描述

点击任意文档链接都可以进入对应的文档

<think>好的,我现在需要帮助用户在pom.xml中添加Swagger的依赖以生成API文档。首先,我得回忆一下SwaggerSpring Boot项目中的常见配置方式。根据用户提供的引用,引用[1]提到在pom.xml中添加io.springfox的springfox-boot-starter依赖,版本3.0.0。而引用[3]则提到使用knife4j-spring-boot-starter,这是一个基于Swagger的工具,可能提供更友好的界面。 用户的需求是集成Swagger相关依赖,所以需要确定使用哪个库。Springfox SwaggerKnife4j都是常见的选择,但它们的依赖项不同。可能需要分别说明两种方式,让用户选择。比如,引用[1][3]分别对应两种不同的依赖,需要正确引用。 接下来,我需要检查依赖的groupIdartifactId是否正确。例如,springfox的groupId是io.springfox,而Knife4j的groupId是com.github.xiaoymin。版本方面,springfox-boot-starter的版本3.0.0是否正确?可能需要注意版本兼容性,比如Spring Boot版本是否支持。但用户没有提到具体版本,所以可能需要给出常用版本,并提示用户根据项目情况调整。 然后,配置类的部分。引用[1][2]提到需要配置Swagger,比如创建配置类,启用Swagger,并设置基本信息。需要确保配置类的代码正确,使用@Configuration@EnableSwagger2或@EnableSwagger2WebMvc等注解,具体取决于使用的库Spring Boot版本。 另外,引用[4][5]提到pom.xml中的依赖管理,比如spring-boot-dependencies的作用,可能需要确认是否需要继承Spring Boot的父项目来管理版本,避免版本冲突。 用户的问题可能涉及到两种集成方式:一种是使用原生的Springfox Swagger,另一种是使用Knife4j增强版。所以,在回答中应该分别给出两种方法的依赖添加步骤,并简要说明它们的区别优势,比如Knife4j提供更好的UI界面。 最后,需要提醒用户访问文档的路径,比如Swagger默认的路径是/swagger-ui.html,而Knife4j可能是/doc.html。同时,检查是否有必要的配置,比如在application.yml中设置启用Swagger,或者处理Spring Security的拦截问题,但用户可能暂时不需要这些,所以可以作为注意事项提及。 总结步骤:1. 添加依赖(两种方式);2. 创建配置类;3. 访问文档路径;4. 注意事项。需要确保每个步骤的代码正确,语法符合要求,比如XML标签闭合,配置类注解正确。同时,根据引用[2],可能需要配置路由,但基本配置可能已经足够。</think>在Spring Boot项目中集成Swagger进行API文档生成,需在`pom.xml`中添加相关依赖并配置基本信息。以下是两种常用方式: --- ### **方式一:使用Springfox Swagger官方依赖** 1. **添加依赖** 在`pom.xml`的`<dependencies>`部分添加以下内容[^1][^2]: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` 2. **配置Swagger** 创建配置类`SwaggerConfig.java`: ```java @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.yourpackage.controller")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API文档") .description("接口说明") .version("1.0") .build(); } } ``` 3. **访问文档** 启动项目后访问:`http://localhost:端口/swagger-ui.html` --- ### **方式二:使用Knife4j增强版** 1. **添加依赖** Knife4j基于Swagger且提供更友好界面,添加依赖[^3]: ```xml <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency> ``` 2. **配置类** 配置类需调整注解Docket类型: ```java @Configuration @EnableSwagger2WebMvc public class Knife4jConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.yourpackage.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Knife4j API文档") .version("1.0") .build(); } } ``` 3. **访问文档** 访问路径为:`http://localhost:端口/doc.html` --- ### **注意事项** 1. 确保Spring Boot版本兼容性(如Spring Boot 2.6+需配置路径匹配策略[^2])。 2. 若项目使用Spring Security,需放行Swagger相关路径(如`/swagger-resources/**`)。 3. 生产环境建议关闭Swagger,可在配置文件中设置`springfox.documentation.enabled=false`[^5]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值