用于弹簧拦截器的Java配置拦截器使用自动assembly的弹簧豆

我想添加spring mvc拦截器作为Java配置的一部分。 我已经有了一个基于xml的配置,但我正在尝试转向Java配置。 对于拦截器,我知道可以从弹簧文档中这样做 –

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

但我的拦截器正在使用一个自动装入它的弹簧豆,如下所示 –

 public class LocaleInterceptor extends HandlerInterceptorAdaptor { @Autowired ISomeService someService; ... } 

SomeService类如下所示 –

 @Service public class SomeService implements ISomeService { ... } 

我正在使用像@Service这样的注释来扫描bean,并且没有在配置类@Bean它们指定为@Bean

据我所知,由于java config使用new来创建对象,spring不会自动将依赖项注入其中。

我如何添加这样的拦截器作为java配置的一部分?

只需执行以下操作:

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

当然, LocaleInterceptor需要在某处配置为Spring bean(XML,Java Config或使用注释),以便注入WebConfig的相关字段。

可以在此处找到Spring的MVC配置的一般自定义文档,特别是拦截器请参阅本节

当您为自己处理对象创建时,如:

 registry.addInterceptor(new LocaleInterceptor()); 

Spring容器无法为您管理该对象,因此需要对LocaleInterceptor进行必要的注入。

对您的情况更方便的另一种方法是在@Configuration声明托管的@Bean并直接使用该方法,如下所示:

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

尝试将您的服务注入构造函数参数。 很简单。

 @EnableWebMvc @Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Autowired ISomeService someService; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LocaleInterceptor(someService)); } } 

然后重新配置你的拦截器,

 public class LocaleInterceptor extends HandlerInterceptorAdaptor { private final ISomeService someService; public LocaleInterceptor(ISomeService someService) { this.someService = someService; } } 

干杯!