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

后端 未结 3 1160
情书的邮戳
情书的邮戳 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:32

    When you handle the object creation for yourself like in:

    registry.addInterceptor(new LocaleInterceptor());
    

    there is no way the Spring container can manage that object for you and therefore make the necessary injection into your LocaleInterceptor.

    Another way that could be more convenient for your situation, is to declare the managed @Bean in the @Configuration and use the method directly, like so:

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

提交回复
热议问题