您当前的位置: 首页 >  spring

springboot2.x+跨域访问+拦截器 配置swagger

发布时间:2020-12-27 23:25:23 ,浏览量:6

创建swagger配置类

因为我的项目是多module,为了能让多module项目中方便引用swagger,所以单独创建了一个swagger-api项目,到时需要引用swagger的项目只需要添加swagger-api的依赖就可以了。 在这里插入图片描述

swagger-api这里创建的是maven项目,在其pom中添加如下依赖

<dependencies>  <dependency> <groupId>io.springfox @Bean public Docket webApiConfig(){ return new Docket(DocumentationType.SWAGGER_2) .groupName("webapi") .apiInfo(webApiInfo()) .select() .paths(Predicates.not(PathSelectors.regex("/admin/.*"))) // 设置不显示项 .paths(Predicates.not(PathSelectors.regex("/error.*"))) .build(); } private ApiInfo webApiInfo(){ return new ApiInfoBuilder() .title("xxx-API文档") .description("本文档描述了xxx中接口定义") .version("1.0") .contact(new Contact("xxx","","xxx@xxx.com")) .build(); } } 

如果你的项目不是多module结构的,只需要在本项目中引入依赖,添加配置类即可

在其他项目中引用swagger

这里我在两个项目中引用了swagger 只需要在引用项目中的pom.xml添加swagger-api的依赖即可 在这里插入图片描述 然后在启动类中添加配置类扫描路径 这里的包路径就是SwaggerConfig配置类的包路径,即图中所示路径,我这里多个module中的路径都一样,所以配置一个就行了 在这里插入图片描述

@ComponentScan(basePackages = { "com.xxx.xxx"}) 

在这里插入图片描述 启动项目后访问 localhost:项目端口/swagger-ui.html 在这里插入图片描述 这里我其中一个module比较单一,没有过多的配置,所以成功启动了。 另外一个项目配置了权限校验,跨域访问,拦截器等访问报错404,所以针对报错开始解决

swagger-ui访问报错404

原因 通过查找资料,了解到404是swagger的静态资源未找到,可能被拦截器拦截了,需要配置过滤 解决

@Configuration @EnableConfigurationProperties(CorsEndpointProperties.class) public class BasicWebConfig implements WebMvcConfigurer { @Autowired UserLogonInterceptor userLogonInterceptor; @Autowired private FunctionPermissionInterceptor permissionInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(userLogonInterceptor).addPathPatterns("/**") .excludePathPatterns("/user/login") // 设置不拦截访问 .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**"); // 权限校验 // registry.addInterceptor(permissionInterceptor).addPathPatterns("/**"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 解决静态资源无法访问 registry.addResourceHandler("/**") .addResourceLocations("classpath:/static/"); // 解决swagger无法访问 registry.addResourceHandler("/swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); // 解决swagger的js文件无法访问
		registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } } 

网上很多报404在这里配置完就解决了,但是我的在这里配置了仍然无法访问,于是继续排查 检查是否有其他拦截器,都做好相应过滤 我这里排查了所有的代码没有发现拦截器未过滤的问题,但还是无法访问,

最终经过几天的陆续排查,发现问题是访问地址的问题,我访问的是localhost:8001/swagger-ui.html,但我的项目是配置了服务名的,所以哪怕本地运行也需要添加上服务名,所以正确的访问地址是localhost:服务端口/服务名/swagger-ui.html. 注意这里根据自己配置而定,如果没有配置服务名就不用添加

关注
打赏
1688896170
查看更多评论

暂无认证

  • 6浏览

    0关注

    115984博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0760s