HandlerInterceptorAdapter和Zuul Filter

问题描述:

可以使用 Zuul 配置添加 HandlerInterceptorAdapter 。我需要拦截对特定资源的请求,但我想因为我有 Zuul 过滤器配置,拦截器永远不会被调用。

It is possible add a HandlerInterceptorAdapter with Zuul Configuration. I need to intercept a request to a specific resource but I suppose because I have Zuul filter configuration, the interceptor is never called.

是可能的这样做?

我试图实现同样的目标。我们有一些Spring MVC控制器和Zuul代理。但我仍然希望使用相同的Interceptor。

I have tried to achieve the same. We have a few Spring MVC controllers and Zuul proxying. But I still wanted the same Interceptor to be used.

这里的问题是zuul在自己的ZuulServlet中运行,并且不会从你的MVC servlet中获取拦截器。 Spring Cloud:ZuulConfiguration.java 配置ZuulHandlerMapping,这是唯一可以设置拦截器的地方,但它不可配置。因此,您需要一个 InstantiationAwareBeanPostProcessorAdapter 来干扰bean的创建,在实例化之后但在初始化之前(在拦截器初始化之前)设置拦截器。

The problem here is that zuul runs in its own ZuulServlet, and does not pick up the interceptors from your MVC servlet. Spring Cloud: ZuulConfiguration.java configures ZuulHandlerMapping, which is the only place interceptors could be set, but it's not configurable. Thus you need a InstantiationAwareBeanPostProcessorAdapter to interfere with the bean creation, to set your interceptors after instantiaton, but before initialization (before the interceptors are initialized).

这对我有用:

@Configuration
@RequiredArgsConstructor
public class ZuulHandlerBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {

    @NonNull
    private final MyInterceptor myInterceptor;

    @Override
    public boolean postProcessAfterInstantiation(final Object bean, final String beanName) throws BeansException {

        if (bean instanceof ZuulHandlerMapping) {

            val zuulHandlerMapping = (ZuulHandlerMapping) bean;
            zuulHandlerMapping.setInterceptors(myInterceptor);
        }

        return super.postProcessAfterInstantiation(bean, beanName);
    }

}