spring拦截器的Java配置,拦截器使用自动连接的SpringBean
我想添加SpringMVC拦截器作为Java配置的一部分。我已经有了一个基于xml的配置,但是我正在尝试使用Java配置。对于拦截器,我从spring文档中知道可以这样做-spring拦截器的Java配置,拦截器使用自动连接的SpringBean,java,spring,spring-mvc,interceptor,Java,Spring,Spring Mvc,Interceptor,我想添加SpringMVC拦截器作为Java配置的一部分。我已经有了一个基于xml的配置,但是我正在尝试使用Java配置。对于拦截器,我从spring文档中知道可以这样做- @EnableWebMvc @Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry)
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleInterceptor());
}
}
但是我的拦截器使用了一个自动连接到它的Springbean,如下所示-
public class LocaleInterceptor extends HandlerInterceptorAdaptor {
@Autowired
ISomeService someService;
...
}
@Service
public class SomeService implements ISomeService {
...
}
SomeService类如下所示-
public class LocaleInterceptor extends HandlerInterceptorAdaptor {
@Autowired
ISomeService someService;
...
}
@Service
public class SomeService implements ISomeService {
...
}
我使用像@Service
这样的注释来扫描Bean,但没有在配置类中将它们指定为@Bean
据我所知,由于JavaConfig使用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
需要在某处配置为Springbean(XML、Java配置或使用注释),以便注入WebConfig
的相关字段
可以找到Spring的MVC配置的一般定制文档,特别是对于拦截器,请参见第节“尝试将您的服务作为构造函数参数注入”。这很简单
@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;
}
}
干杯 当您自己处理对象创建时,如:
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() );
}
}
这在Spring 3.2.12中对我有效,但被接受的答案没有。我看不出两者之间的区别,因为这一条至少解释了问题的原因。不再有效,因为它是在@Haroldo_Ok之后编辑的,以便在Spring 3.2.12中起作用,我必须将
@Component
添加到我的localeiinterceptor
@Nathan中,这是正确的。如果您使用类路径扫描来创建一个LocaleInterceptor
,它是一个Springbean,那么您自然需要@组件
注释。否则,您可以用XML或Java配置Springbean。您知道Spring文档(而不是JavaDoc)在哪里提到过这一点吗?整个WebMVCConfigureAdapter的东西。@ecbrodie问得好!请查看我更新的链接答案!拒绝投票的原因:如果您尝试在拦截器类内注入(Autowire)Spring存储库bean并尝试调用JPAEEntityManager,这种方法会导致“循环依赖注入问题”