Java config for spring interceptor where interceptor is using autowired spring beans

后端 未结 3 1159
情书的邮戳
情书的邮戳 2020-12-08 14:01

I want to add spring mvc interceptor as part of Java config. I already have a xml based config for this but I am trying to move to a Java config. For interceptors, I know th

3条回答
  •  北海茫月
    2020-12-08 14:39

    Just do the following:

    @EnableWebMvc
    @Configuration
    public class WebConfig extends WebMvcConfigurerAdapter {
    
        @Bean
        LocaleInterceptor localInterceptor() {
             return new LocalInterceptor();
        }
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(localeInterceptor());
        }
    
    }
    

    Of course LocaleInterceptor needs to be configured as a Spring bean somewhere (XML, Java Config or using annotations) in order for the relevant field of WebConfig to get injected.

    The documentation for general customization of Spring's MVC configuration can be found here, and specifically for Interceptors see this section

提交回复
热议问题