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

别等时光非礼了梦想. 提交于 2019-11-28 07:16:43
geoand

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

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() );
    }
}

Try to inject your service as a constructor parameter. It is simple.

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

   @Autowired
   ISomeService someService;

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

}

Then reconfigure your interceptor,

public class LocaleInterceptor extends HandlerInterceptorAdaptor {


     private final ISomeService someService;

     public LocaleInterceptor(ISomeService someService) {
         this.someService = someService;
     }


}

Cheers !

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!