用于弹簧拦截器的Java配置拦截器使用自动装配的弹簧豆 [英] Java config for spring interceptor where interceptor is using autowired spring beans
问题描述
我想添加spring mvc拦截器作为Java配置的一部分。我已经有了一个基于xml的配置,但我正在尝试转向Java配置。对于拦截器,我知道可以从spring文档中这样做 -
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 that it can be done like this from the spring documentation-
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleInterceptor());
}
}
但我的拦截器正在使用弹簧bean自动装入如下 -
But my interceptor is using a spring bean autowired into it like follows-
public class LocaleInterceptor extends HandlerInterceptorAdaptor {
@Autowired
ISomeService someService;
...
}
SomeService类看起来像跟随 -
The SomeService class looks like follows-
@Service
public class SomeService implements ISomeService {
...
}
我使用的注释如 @Service
用于扫描bean并且未在配置类中指定它们为 @Bean
I am using annotations like @Service
for scanning the beans and have not specified them in the configuration class as @Bean
正如我的理解由于java config使用new来创建对象,因此spring不会自动将依赖项注入其中。
As my understanding, since java config uses new for creating the object, spring will not automatically inject the dependencies into it.
如何在java配置中添加这样的拦截器?
How can I add the interceptors like this as part of the java config?
推荐答案
只需执行以下操作:
@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
的相关字段注入。
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.
可以找到Spring的MVC配置的一般自定义文档这里,特别是拦截器,请参阅这个部分
The documentation for general customization of Spring's MVC configuration can be found here, and specifically for Interceptors see this section
这篇关于用于弹簧拦截器的Java配置拦截器使用自动装配的弹簧豆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!