【问题标题】:MappedInterceptor Bean Vs WebMvcConfigurer addInterceptors. What is the correct (modern) way for adding Spring HandlerInterceptor?MappedInterceptor Bean 与 WebMvcConfigurer addInterceptors。添加 Spring HandlerInterceptor 的正确(现代)方法是什么?
【发布时间】:2021-11-02 20:54:29
【问题描述】:

我偶然发现了一个项目的配置类,该项目从传统的 spring 转换为 Spring Boot。我看到有两种添加拦截器的方法。喜欢这些

  @Configuration
  public class AppConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
     registry.addInterceptor( new MyInterceptorOne()).addPathPatterns("/api/data/**");
    }

    @Bean
    public MappedInterceptor mappedResponseHeaderInterceptor() {
        return new MappedInterceptor(new String[] { "/static/css/**", "/static/img/**" }, new ResponseHeaderInterceptor());
    }
  }
  

两个拦截器都在工作。我想知道在 Spring Boot 中添加拦截器的正确方法是什么以及为什么存在这两种方法

【问题讨论】:

  • 两者都有效,您首先在内部使用MappedInterceptor。所以或多或少它们是相同的,第一个更容易并且应该使用。这实际上只起作用,因为 Spring Boot 在上下文中检测到 HandlerInterceptor 实例并自动注册它们,这在普通的 Spring 应用程序中不起作用。

标签: java spring spring-boot spring-mvc


【解决方案1】:

基本上它们是相同的。

registry.addInterceptor( new MyInterceptorOne()).addPathPatterns("/api/data/**");

将在内部使用MappedInterceptorHandlerInterceptor 注册到给定的URL 模式。

现在将HandlerInterceptorMappedInterceptor 实现)注册为@Bean 可以正常工作,因为 Spring Boot(不是普通的 Spring!)在上下文中检测到 HandlerInterceptor bean 并自动为您注册它们。这在常规 Spring 应用程序中不起作用。

所以使用方法是使用InterceptorRegistry,因为这是记录的方式,MappedInterceptor 更多的是内部支持类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 2021-04-06
    • 2014-11-06
    • 1970-01-01
    相关资源
    最近更新 更多