且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

HandlerInterceptorAdapter和Zuul Filter

更新时间:2023-12-04 11:05:34

我试图实现同样的目标。我们有一些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);
    }

}