解决SpringBoot2.x添加拦截器后Swagger无法访问

博客主要介绍Spring Boot拦截器的配置,包括1.x和2.x的配置方式,指出在Spring Boot 2.x中WebMvcConfigurerAdapter已被弃用,更好做法是实现WebMvcConfigurer接口,还提到自定义拦截器。此外,说明了添加拦截器后Swagger无法访问的问题及解决办法,即配置swagger资源路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、配置拦截器

(1)SpringBoot 1.x配置方式

@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
	@Resource
	private FRInterceptor fRInterceptor;
 
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		//自定义拦截器,添加拦截路径和排除拦截路径 
	registry.addInterceptor(fRInterceptor)
            .addPathPatterns("api/**")
            .excludePathPatterns("api/login");
}

(2)SpringBoot 2.x配置方式

       但是在spring boot2.x中,WebMvcConfigurerAdapter被deprecated,虽然继承WebMvcConfigurerAdapter这个类虽然有此便利,但在Spring5.0里面已经deprecated了。

     官方文档也说了,WebMvcConfigurer接口现在已经有了默认的空白方法,所以在Springboot2.0(Spring5.0)下更好的做法还是implements WebMvcConfigurer。
 

@Configuration
public class WebConfig implements WebMvcConfigurer {
	@Resource
	private FileUploadInterceptor fileUploadInterceptor;
 
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 自定义拦截器,添加拦截路径和排除拦截路径
		registry.addInterceptor(fileUploadInterceptor).addPathPatterns("/**");
	}
}

(3)自定义拦截器

@Component
public class FileUploadInterceptor implements HandlerInterceptor {
	/*
	 * 视图渲染之后的操作
	 */
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
 
	}
 
	/*
	 * 处理请求完成后视图渲染之前的处理操作
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
 
	}
 
	/*
	 * 进入controller层之前拦截请求
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		System.out.println("getContextPath:" + request.getContextPath());
		System.out.println("getServletPath:" + request.getServletPath());
		System.out.println("getRequestURI:" + request.getRequestURI());
		System.out.println("getRequestURL:" + request.getRequestURL());
		System.out.println("getRealPath:" + request.getSession().getServletContext().getRealPath("image"));
		return true;
	}
 
}

 

二、添加拦截器后Swagger无法访问

在配置拦截器的时候,配置swagger资源路径

@Configuration
public class InteceptorConfig implements WebMvcConfigurer {
    @Autowired
    EnvironmentConfig environmentConfig;
    @Resource
    private AccessCheckInteceptor accessCheckInteceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 自定义拦截器,添加拦截路径和排除拦截路径
        String excludePathStr = environmentConfig.getConfigEnvironment();
        String[] excludePathArr = excludePathStr.split(",");
        registry.addInterceptor(accessCheckInteceptor)
                // 排除配置
                .excludePathPatterns(excludePathArr)
                // 拦截配置
                .addPathPatterns("/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");
        // 放行swagger
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

 

 

 

 

 

### Spring Boot 2.7.x 整合 Swagger 配置教程 #### 1. 添加 Maven 或 Gradle 依赖 为了在 Spring Boot 2.7.x 中集成 Swagger,需要引入 `springfox-boot-starter` 的依赖。以下是具体的 Maven 和 Gradle 配置: 对于 Maven 用户: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` 对于 Gradle 用户: ```gradle implementation 'io.springfox:springfox-boot-starter:3.0.0' ``` 上述依赖会自动导入所需的组件来支持 Swagger 功能[^1]。 --- #### 2. 启用 Swagger 注解 在项目的主类上添加 `@EnableOpenApi` 注解以启用 Swagger 支持功能。如果使用的是较旧版本的 Springfox,则可能需要使用 `@EnableSwagger2` 注解[^2]。 示例代码如下: ```java import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @EnableSwagger2 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` --- #### 3. 解决常见错误 当尝试运行项目时可能会遇到以下警告信息: ``` WARN ... Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException... ``` 此问题是由于某些路径未被正确解析所致。可以通过调整配置文件中的静态资源拦截器设置来解决问题[^3]。 解决方案是在 `application.properties` 文件中添加以下内容: ```properties spring.mvc.pathmatch.matching-strategy=ant_path_matcher ``` 这一步骤确保了 Spring MVC 路径匹配策略兼容 Swagger 所需的行为模式。 --- #### 4. 自定义 API 文档信息 通过创建一个 Bean 来自定义 Swagger UI 显示的信息,例如标题、描述和联系人详情等。具体实现方式如下所示: ```java import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class OpenApiConfig { @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info(new Info() .title("Sample API Documentation") // 设置文档标题 .description("This document describes the APIs of Sample Project.") // 描述说明 .version("1.0")); // 版本号 } } ``` 以上代码片段用于生成更友好的 API 接口展示页面。 --- #### 5. 访问 Swagger UI 页面 完成上述步骤后,启动应用程序并访问以下 URL 即可查看 Swagger 提供的交互式接口文档界面: ``` http://localhost:8080/swagger-ui/index.html#/home ``` 注意:默认情况下,Springfox 将提供 `/v3/api-docs` 地址作为 JSON 格式的开放 API 数据源。 --- #### 6. 过滤特定请求路径 有时希望排除部分控制器或方法不显示于最终生成的文档之中。此时可通过编写 Docket 对象实例化逻辑达成目标。下面是一个简单的例子演示如何隐藏指定包下的所有端点: ```java @Bean public Docket apiDocket() { return new Docket(DocumentationType.OAS_30) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 只扫描该包内的Controller .paths(PathSelectors.any()) .build(); } ``` 这样能够更加精确控制哪些 RESTful Service 展现给外部调用者知晓。 --- ### 注意事项 - 如果仍然存在异常情况,请确认所使用的 Spring Boot 和 Springfox 版本完全一致适配关系。 - 建议阅读官方最新发布指南获取更多高级特性介绍资料链接地址。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值