繁体   English   中英

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

[英]Java config for spring interceptor where interceptor is using autowired spring beans

我想添加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配置使用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;
     }


}

干杯!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM