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

时间:2014-04-28 19:01:52

标签: java spring spring-mvc interceptor

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

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

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

}

但是我的拦截器正在使用一个自动装入它的spring bean,如下所示 -

public class LocaleInterceptor extends HandlerInterceptorAdaptor {

    @Autowired
    ISomeService someService;

    ...
}

SomeService类如下所示 -

@Service
public class SomeService implements ISomeService {

   ...
}

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

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

如何在java配置中添加这样的拦截器?

3 个答案:

答案 0 :(得分:46)

请执行以下操作:

@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配置的一般自定义文档here,特别是对于拦截器,请参阅this部分

答案 1 :(得分:14)

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

registry.addInterceptor(new LocaleInterceptor());

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

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

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public LocaleInterceptor localeInterceptor() {
        return new LocaleInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor( localeInterceptor() );
    }
}

答案 2 :(得分:7)

尝试将服务作为构造函数参数注入。这很简单。

@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;
     }


}

干杯!

相关问题