在没有WebMvcConfigurationSupport的情况下注册Spring HandlerInterceptor [英] Register Spring HandlerInterceptor Without WebMvcConfigurationSupport

查看:110
本文介绍了在没有WebMvcConfigurationSupport的情况下注册Spring HandlerInterceptor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java Config 在Spring中注册 HandlerInterceptor 的实例,而不使用扩展 WebMvcConfigurationSupport 。我正在创建一个带有注释的库,当添加到 @Configuration 类时,会注册一个处理安全注释的拦截器。

I'm trying to register an instance of HandlerInterceptor in Spring using Java Config without extending WebMvcConfigurationSupport. I'm creating a library with an annotation that, when added to a @Configuration class, registers an interceptor that handles a security annotation.

我有一个使用 WebMvcConfigurationSupport#addInterceptors 的实现,但这与Spring中的其他自动工作冲突,并覆盖了一些应用程序自己的逻辑。对于应该简单的事情来说,它似乎也非常沉重。我现在正在尝试:

I had an implementation using WebMvcConfigurationSupport#addInterceptors, but that conflicted with other automatic workings in spring, and overrode some of the application's own logic. It also seems incredibly heavy for something that should be simple. I'm now trying:

@Configuration
public class AnnotationSecurityConfiguration {

    @Autowired private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @PostConstruct
    public void attachInterceptors() {
        requestMappingHandlerMapping.setInterceptors(new Object[] {
                new SecurityAnnotationHandlerInterceptor()
        });
    }

}

然而,似乎是拦截器使用与应用程序实际用于Web请求的实例完全不同的 RequestMappingHandlerMapping 实例进行注册。另外,当实现为 BeanFactoryPostProcessor 时,我在 HealthMvcEndpoint NullPointerException $ c>当我尝试 beanFactory.getBean(RequestMappingHandlerMapping.class)

However, it appears that the interceptor gets registered with a completely different instance of RequestMappingHandlerMapping than the one the application actually uses for web requests. Additionally, when implemeted as a BeanFactoryPostProcessor, I get a NullPointerException in HealthMvcEndpoint when I try beanFactory.getBean(RequestMappingHandlerMapping.class)

推荐答案

编辑:此类已被弃用。有关Spring 5的等效内容,请参阅下面的 @bosco答案

Edit: This class has since been deprecated. See @bosco answer below for the Spring 5 equivalent.

弄清楚,解决方案是使用,简单地说:

Figured it out, the solution is to use, simply:

@Configuration
public class AnnotationSecurityConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SecurityAnnotationHandlerInterceptor());
    }

}

在春季启动时,所有豆子都是类型 WebMvcConfigurer 会被自动检测到并可以修改MVC上下文。

In spring boot, all beans of type WebMvcConfigurer are automatically detected and can modify the MVC context.

这篇关于在没有WebMvcConfigurationSupport的情况下注册Spring HandlerInterceptor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆