栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot拦截器自动配置原理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot拦截器自动配置原理

  1.拦截器配置

        通过WebMvcConfigurer配置拦截器

@Configuration
public class WebMvcConfigurerImpl implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new FirstInterceptor()).addPathPatterns("/hello");
    }
}

class FirstInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

        访问/hello请求,并进入断点:

(1)进入DispatcherServlet的doDispatch()方法

springboot底层就是使用springmvc的DispatcherServlet类处理请求的

HandlerExecutionChain里面封装的就是当前请求的处理器Object对象和拦截器列表

(2)进入getHandler()

看他如何封装HandlerExecutionChain:

protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
   if (this.handlerMappings != null) {
      for (HandlerMapping mapping : this.handlerMappings) {
          //HandlerMapping接口用于定义请求和处理程序对象之间的映射
          //遍历当前Servlet中的List handlerMappings,寻找合适的HandlerMapping
          //当前合适的mapping是RequestMappingHandlerMapping
         HandlerExecutionChain handler = mapping.getHandler(request);
         if (handler != null) {
            return handler;
         }
      }
   }
   return null;
}

先看一下HandlerMapping的结构图:

不同的HandlerMapping表示处理不同的映射请求

 (3)进入mapping.getHandler()

 看他如何处理的

主要看断点的那一行

可以看出该请求对应的handler已经匹配到, handler: "com.controller.IndexController#hello()",也就是我们的控制器方法

(4)再进入getHandlerExecutionChain()

看他如何匹配HandlerExecutionChain对应的拦截器,并返回HandlerExecutionChain对象

 

添加完拦截器后,返回HandlerExecutionChain,在后续中就会被调用拦截,这就是拦截器的大致流程

2.拦截器自动配置原理

这里主要有两个问题:

1.这个HandlerMapping中this.adaptedInterceptors拦截器列表是如何创建的

2.我们创建的拦截器怎么被封装到MappedInterceptor中,MappedInterceptor也实现了HandlerInterceptor接口

要解决上面问题,就要提到springboot的自动配置,springboot中自动配置web和DispatcherServlet的配置类主要是:

1.WebMvcAutoConfiguration

2.DispatcherServletAutoConfiguration

主要看WebMvcAutoConfiguration

@Configuration(proxyBeanMethods = false) //表示这是一个配置类
@ConditionalOnWebApplication(type = Type.SERVLET) //只有基于servlet的web应用程序才会配置
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class }) //这两个类程序中也是有的
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)//容器中没有WebMvcConfigurationSupport类型时才会配置,肯定没有下面有查看
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
		ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

	
	@Configuration(proxyBeanMethods = false)
	public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {
		
        //主要看这个
        //用于注入RequestMappingHandlerMapping,前面请求用到的就是这个HandlerMapping
        @Bean
		@Primary
		@Override
		public RequestMappingHandlerMapping requestMappingHandlerMapping(
				@Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager,
				@Qualifier("mvcConversionService") FormattingConversionService conversionService,
				@Qualifier("mvcResourceUrlProvider") ResourceUrlProvider resourceUrlProvider) {
			// Must be @Primary for MvcUriComponentsBuilder to work
			return super.requestMappingHandlerMapping(contentNegotiationManager, conversionService,
					resourceUrlProvider);
		}

        //返回一个RequestMappingHandlerMapping对象,通过上面方法被注入
		@Override
		protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() {
			if (this.mvcRegistrations != null && this.mvcRegistrations.getRequestMappingHandlerMapping() != null) {
				return this.mvcRegistrations.getRequestMappingHandlerMapping();
			}
			return super.createRequestMappingHandlerMapping();
		}

	}

    
    //..........省略其他............
}

 验证@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)

public class Main {
    public static void main(String[] args) {
        //返回IOC容器
        ConfigurableApplicationContext context = SpringApplication.run(Main.class, args);

        WebMvcConfigurationSupport webMvcConfigurationSupport =
                context.getBean(WebMvcConfigurationSupport.class);
        //容器中WebMvcConfigurationSupport类型实例是他的子类
        //打印: org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration
        System.out.println(webMvcConfigurationSupport.getClass());
    }
}

上面自动配置类中的requestMappingHandlerMapping()实际调用了他父类WebMvcConfigurationSupport的方法

public class WebMvcConfigurationSupport implements ApplicationContextAware, ServletContextAware {

	public RequestMappingHandlerMapping requestMappingHandlerMapping(
      	@Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager,
      	@Qualifier("mvcConversionService") FormattingConversionService conversionService,
      	@Qualifier("mvcResourceUrlProvider") ResourceUrlProvider resourceUrlProvider) {

    	//....省略.....
    	RequestMappingHandlerMapping mapping = createRequestMappingHandlerMapping();
        //这个方法就用于设置拦截器了,再调用的是下面方法
   		mapping.setInterceptors(getInterceptors(conversionService, resourceUrlProvider));
        
		//....省略.....
        
   		return mapping;
	}
    
    protected final Object[] getInterceptors(
			FormattingConversionService mvcConversionService,
			ResourceUrlProvider mvcResourceUrlProvider) {
		if (this.interceptors == null) {
            //这个类就很熟悉了
			InterceptorRegistry registry = new InterceptorRegistry();
            //这个也是添加拦截器 调用他实现类DelegatingWebMvcConfiguration中的,它本身是个空方法
            //这里添加我们自定义的拦截器
			addInterceptors(registry);
			
			registry.addInterceptor(new ConversionServiceExposingInterceptor(mvcConversionService));
			registry.addInterceptor(new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider));
			this.interceptors = registry.getInterceptors();
		}
		return this.interceptors.toArray();
	}
    
    //什么也没写
    protected void addInterceptors(InterceptorRegistry registry) {
	}
}

进入DelegatingWebMvcConfiguration.addInterceptors()

 从上图可以看出DelegatingWebMvcConfiguration是他子类

@Configuration(proxyBeanMethods = false)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

    //创建封装WebMvcConfigurer配置的组合类,当前是空的
	private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();

    //注入容器中所有WebMvcConfigurer类型,并添加到组合类中
    //我们自定义的WebMvcConfigurer配置类也会被注入
	@Autowired(required = false)
	public void setConfigurers(List configurers) {
		if (!CollectionUtils.isEmpty(configurers)) {
			this.configurers.addWebMvcConfigurers(configurers);
		}
	}
    
	@Override
	protected void addInterceptors(InterceptorRegistry registry) {
         //这里就依次调用组合类中WebMvcConfigurer的addInterceptors()方法
   		this.configurers.addInterceptors(registry);
       
	}
}

WebMvcConfigurerComposite是什么:

//委托List delegates去执行
class WebMvcConfigurerComposite implements WebMvcConfigurer {

   private final List delegates = new ArrayList<>();

   public void addWebMvcConfigurers(List configurers) {
      if (!CollectionUtils.isEmpty(configurers)) {
         this.delegates.addAll(configurers);
      }
   }
}

自动配置执行完后,就将所有拦截器添加到了RequestMappingHandlerMapping的这个变量中

public class RequestMappingHandlerMapping{

	private final List interceptors = new ArrayList<>();
    
} 

而我们实际匹配拦截器时用的是下面这个变量,它里面其实通过方法将this.interceptors赋值给了this.adaptedInterceptors

public class RequestMappingHandlerMapping{

	private final List adaptedInterceptors = new ArrayList<>();
    
}

奇怪的是我们自定义的HandlerInterceptor被封装到了MappedInterceptor中

查看WebMvcConfigurationSupport.getInterceptors()方法:

 但是通过计算registry.getInterceptors()得到的是MappedInterceptor对象,这里封装的才是我们自定义的

 进入registry.getInterceptors()方法:

protected List getInterceptors() {
    //这里就不深究了
   return this.registrations.stream()
         .sorted(INTERCEPTOR_ORDER_COMPARATOR)
         .map(InterceptorRegistration::getInterceptor)
         .collect(Collectors.toList());
} 

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号