目的:對get請求添加token驗證(若為post請求可通過RequestBodyAdvice實現)。
情景:因為有api版本管理的需求,重寫了WebMvcConfigurationSupport類的requestMappingHandlerMapping()方法,沒有使用<mvc:annotation-driven/>標簽,或@EnableWebMvc注解。
方案1:mvc的xml中配置mvc:interceptors標簽,發現無論是設置全局還是特定請求攔截都沒有生效。
方案2:類似springBoot中的攔截器設置,通過重寫WebMvcConfigurerAdapter的addInterceptors方法實現,發現依然沒有效果。
方案3:在繼承的requestMappingHandlerMapping()方法中new出一個InterceptorRegistry,添加Interceptor后addInterceptors,setInterceptors,仍然無效。
最后,在繼承WebMvcConfigurationSupport類時同時重寫addInterceptors方法,終於成功。
問題暫時解決,但是xml中的配置沒有用了嗎?WebMvcConfigurerAdapter在SpringMVC4中也不好用?有時間需要閱讀源碼,探究調用關系。