0


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配置类

importio.swagger.annotations.ApiOperation;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.BeansException;importorg.springframework.beans.factory.config.BeanPostProcessor;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.util.ReflectionUtils;importorg.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;importorg.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;importspringfox.documentation.builders.ApiInfoBuilder;importspringfox.documentation.builders.ParameterBuilder;importspringfox.documentation.builders.PathSelectors;importspringfox.documentation.builders.RequestHandlerSelectors;importspringfox.documentation.schema.ModelRef;importspringfox.documentation.service.ApiInfo;importspringfox.documentation.service.Contact;importspringfox.documentation.service.Parameter;importspringfox.documentation.spi.DocumentationType;importspringfox.documentation.spring.web.plugins.Docket;importspringfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;importspringfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;importspringfox.documentation.swagger2.annotations.EnableSwagger2;importjava.lang.reflect.Field;importjava.util.ArrayList;importjava.util.List;importjava.util.stream.Collectors;@Slf4j@Configuration@EnableSwagger2@Profile({"test"})//在啥样的配置文件环境生效publicclassSwagger2ConfigimplementsWebMvcConfigurer{/**
     * 显示swagger-ui文档展示页,还必须注入swagger资源:
     *
     * @param registry
     */@OverridepublicvoidaddResourceHandlers(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
     */@BeanpublicDocketuserSecurity(){returnnewDocket(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
     */privateApiInfoapiInfo(){returnnewApiInfoBuilder().title("XX项目").description(" API 1.0 操作文档").termsOfServiceUrl("").version("1.0").contact(newContact("葵花宝典","","[email protected]")).build();}/**
     * 设置请求头
     *
     * @return
     */privateList<Parameter>setRequestHeaders(){ParameterBuilder ticketPar =newParameterBuilder();List<Parameter> pars =newArrayList<Parameter>();
        ticketPar.name("X-Access-Token").description("用户token").modelRef(newModelRef("string")).parameterType("header").required(false).build();//header中的ticket参数非必填,传空也可以
        pars.add(ticketPar.build());//根据每个方法名也知道当前方法在设置什么参数return pars;}@BeanpublicstaticBeanPostProcessorspringfoxHandlerProviderBeanPostProcessor(){returnnewBeanPostProcessor(){@OverridepublicObjectpostProcessAfterInitialization(Object bean,String beanName)throwsBeansException{if(bean instanceofWebMvcRequestHandlerProvider|| bean instanceofWebFluxRequestHandlerProvider){customizeSpringfoxHandlerMappings(getHandlerMappings(bean));}return bean;}private<TextendsRequestMappingInfoHandlerMapping>voidcustomizeSpringfoxHandlerMappings(List<T> mappings){List<T> copy = mappings.stream().filter(mapping -> mapping.getPatternParser()==null).collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);}@SuppressWarnings("unchecked")privateList<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){thrownewIllegalStateException(e);}}};}}

3.启动类输出文档地址

@Slf4j@SpringBootApplicationpublicclassJinyiSecurityApplication{publicstaticvoidmain(String[] args)throwsUnknownHostException{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见下图
在这里插入图片描述

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

标签: spring boot html ui

本文转载自: https://blog.csdn.net/huangchong0107/article/details/128685628
版权归原作者 哈喽,树先生 所有, 如有侵权,请联系我们删除。

“swagger 3.0.0 集成 springboot 2.6+ 生成doc.html 和swagger-ui”的评论:

还没有评论