我正在努力寻找一种方法来从一个或多个附加模块中添加请求拦截器(在这种情况下,模块是Maven模块)。
在主模块中,有一个Web MVC配置类,如下所示:
@Configuration
public class WebMvcConfig extends DelegatingWebMvcConfiguration {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// main module interceptors are registered here via
// registry.addInterceptor(interceptor);
}
}
现在,在附加模块1中,我有MyFirstCustomInterceptor
和附加模块2 MySecondCustomInterceptor
,我想将其添加到同一个拦截器注册表中。我觉得这应该很简单,但在阅读官方的Spring MVC文档时,我找不到明显的方法。
在文档中提到并且听起来很有希望的一种方法是使用RequestMappingHandlerMapping
bean及其setInterceptors(Object[] interceptors)
方法。
我尝试将bean注入应用程序启动的事件侦听器类并通过requestMappingHandlerMapping.setInterceptors(myCustomerInterceptorArray)
添加自定义拦截器。不幸的是,这并没有奏效。似乎正在添加拦截器,但Spring使用另一个拦截器列表 - adaptedInterceptors
- 用于执行链。不幸的是,似乎没有任何公共方法可以将拦截器添加到adaptedInterceptors
列表中。
我在想,可能需要先调用RequestMappingHandlerMapping.setInteceptors()
方法,或者必须有一种方法将WebMvcConfig扩展到附加模块。但我不确定如何做到这一点。
修改
我刚才拥有的另一个想法是基于注入所有HandlerInterceptor
bean的列表。例如:
@Configuration
public class WebMvcConfig extends DelegatingWebMvcConfiguration {
@Inject private List<HandlerInterceptor> handlerInterceptors;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// Note: the order of the interceptors would likely be an issue here
for (HandlerInterceptor interceptor : handlerInterceptors) {
registry.addInterceptor(interceptor);
}
}
}
这种方法的唯一问题是没有一种非常好的方法来命令拦截器。这可以通过自定义解决方案来解决,例如在每个拦截器类上添加订单注释,并在将它们添加到注册表时将其考虑在内。但它仍然感觉不到100%干净。所以我仍然希望有更好的方法。
答案 0 :(得分:0)
通常在使用Spring MVC时,您应该有一个基于配置的类@EnableWebMvc
。
这将在您的根配置
中@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// Add the interceptors for the root here.
}
}
现在,在您的其他项目中,只需添加一个仅添加拦截器的配置类。
@Configuration
public class ModuleAWebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// Add the interceptors for the Module A here.
}
}
配置Spring @MVC时会查询所有WebMvcConfigurer
。
但是,在您的情况下,由于您已经覆盖了DelegatingWebMvcConfiguration
,因为您已经扩展了addInterceptors
并且因为您已经覆盖protected void addInterceptors(InterceptorRegistry registry) {
this.configurers.addInterceptors(registry);
}
方法而破坏了委托,因此无法正常工作。
该方法的默认实现是
configurers
咨询所有WebMvcConfigurer
(检测到的{{1}})。但是由于你的覆盖方法,这种情况不再发生,而且正常的扩展机制已经不再适用了。