2:swagger3集成xiaoymin ui的示例

  1. maven依赖
            <!-- https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter/3.0.0 -->
            <!-- 参考 https://stackoverflow.com/questions/62773219/suddenly-springfox-swagger-3-0-is-not-working-with-spring-webflux -->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-boot-starter</artifactId>
                <version>3.0.0</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/com.github.xiaoymin/knife4j-spring-ui -->
            <!-- http://localhost:8080/doc.html -->
            <dependency>
                <groupId>com.github.xiaoymin</groupId>
                <artifactId>knife4j-spring-ui</artifactId>
                <version>3.0.3</version>
            </dependency>
    

  2. 代码

    @SpringBootApplication
    public class Application implements WebMvcConfigurer {
    	public static void main(String[] args) {
    		SpringApplication.run(Application.class, args);
    	}
    	@Bean
    	public Docket createRestApi() {
    		return new Docket(DocumentationType.OAS_30)
    				.apiInfo(new ApiInfoBuilder()
    						.description("面试")
    						.title("标题")
    						.version("版本 1.0.0")
    						.build())
    				.groupName("测试组")
    				.enable(true)
    				.select()
    				.apis(RequestHandlerSelectors.basePackage("com.demo"))
    				.paths(PathSelectors.any())
    				.build();
    	}
    
    }
    

  3. 效果

@Bean
    public Docket docket(Environment environment) {

        // 设置了swagger的docket的环境
        boolean flag = environment.acceptsProfiles(Profiles.of("dev", "test", "prod"));

        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .groupName("g_name")
                .enable(flag)
                .select()
                // 指定要扫描的包
                .apis(RequestHandlerSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact("authorName", "www.baidu.com", "111111@qq.com");

        return new ApiInfo("Api文档", "Api文档",
                "1.0", "www.baidu.com",
                contact, "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<VendorExtension>());
    }

二:2023年04月22日15:13:26: 更新springboot 2.7.x swagger 界面不显示的问题

2.1: 

springfox.documentation.swagger-ui.enabled=true
knife4j.enable=true
knife4j.production=false
spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER

2.2: code


import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.google.common.base.Preconditions;
import com.morris.learn.util.CastUtil;
import com.morris.learn.global.GlobalInterceptor;
import com.morris.learn.log.TraceIdInterceptor;
import lombok.RequiredArgsConstructor;
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.core.env.Environment;
import org.springframework.lang.NonNull;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
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 java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Configuration
@RequiredArgsConstructor
@EnableOpenApi
@EnableKnife4j
public class WebConfig implements WebMvcConfigurer {

//    private final GlobalInterceptor globalInterceptor;
//    private final TraceIdInterceptor traceIdInterceptor;
//
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        registry.addInterceptor(traceIdInterceptor);
//        registry.addInterceptor(globalInterceptor);
//    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 覆盖所有请求
        registry.addMapping("/**")
                // 允许发送 Cookie
                .allowCredentials(true)
                // 放行哪些域名(必须用 patterns,否则 * 会和 allowCredentials 冲突)
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
    @Bean
    public Docket docket() {

        // 设置了swagger的docket的环境

        return new Docket(DocumentationType.OAS_30).apiInfo(apiInfo()).groupName("g_name").select()
                // 指定要扫描的包
                .apis(RequestHandlerSelectors.basePackage("com.morris.learn")).paths(PathSelectors.any()).build()
                ;
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact("authorName", "www.baidu.com", "111111@qq.com");

        return new ApiInfo("Api文档", "Api文档", "1.0", "www.baidu.com",
                contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList<>());
    }

    @Bean
    public static BeanPostProcessor springfoxHandler() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    Preconditions.checkNotNull(field, "filed can not be null");
                    field.setAccessible(true);
                    try {
                        List<RequestMappingInfoHandlerMapping> mappings = CastUtil.cast(field.get(bean));
                        List<RequestMappingInfoHandlerMapping> copy = mappings.stream().filter(mapping -> mapping.getPatternParser() == null).collect(Collectors.toList());
                        mappings.clear();
                        mappings.addAll(copy);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
                return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
            }
        };

    }
}

2.3: util:

/**
 * @author Fanhaibo 2023-04-22 13:38:10
 *
 */
@SuppressWarnings("ALL")
public class CastUtil {


    /**
     * 方便强转
     */
    public static <T> T cast(Object obj) {
        return (T) obj;

    }
}


代码参考链接:https://blog.csdn.net/qq_40663787/article/details/106333663

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据引用中的内容,解决swagger2.9.2报错 For input string: "" 的问题时,可以尝试将swagger的annotations以及models替换为1.5.21版本。在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> <exclusions> <exclusion> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> </exclusion> <exclusion> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>1.5.22</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>1.5.22</version> </dependency> ``` 这样,你就能解决swagger2.9.2报错 For input string: "" 的问题了。如果你还遇到swagger不能传递参数的问题,可以参考引用中提供的博客链接,了解解决方案。 在使用swagger传递参数时,你可以使用@ApiParam注解,如引用所示。在方法的参数上添加@ApiParam注解,指定参数的名称、值和是否必需。这样,你就能够在swagger中正确传递参数了。但如果你仍然遇到Cannot resolve io.springfox:springfox-swagger-ui:unknown的问题,可能是你的项目中没有正确引入swagger-ui的依赖。你可以检查一下你的pom.xml文件,确保有以下依赖的配置: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> ``` 这样,你就能够解决Cannot resolve io.springfox:springfox-swagger-ui:unknown的问题了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [解决idea中添加依赖遇见Cannot resolve XXX的问题](https://blog.csdn.net/qq_56392291/article/details/131025683)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [swagger使用问题收集](https://blog.csdn.net/DATANGguanjunhou/article/details/102733213)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值