如何在spring boot webapplication中配置2个单独的过滤器?

时间:2016-09-14 08:27:29

标签: java spring spring-mvc filter spring-boot

我正在尝试在Spring启动配置中使用FilterRegistrationBean添加2个单独的过滤器。

以下是我对2个过滤器的实现。

UPDATE liverpool.master_person mp
  JOIN (SELECT Master_Person_ID, count(*) as cnt
          FROM liverpool.person_record
         GROUP BY Master_Person_ID)
       ) pr
    ON mp.Master_Person_ID = pr.Master_Person_ID
   SET mp.Link_Count = pr.cnt - 1

但是它给出了以下错误并且无法启动应用程序上下文。 请让我知道如何实现同样的目标。

Caused by: org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'featureAccessFilter': 
Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: 
private org.springframework.boot.context.embedded.FilterRegistrationBean com.beroe.insync2.config.FeatureAccessFilter.filterRegistrationBean; 
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: 
No qualifying bean of type [org.springframework.boot.context.embedded.FilterRegistrationBean] is defined: 
expected single matching bean but found 2: someFilterRegistration,shareFilterRegistration
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)

1 个答案:

答案 0 :(得分:1)

Bean按类型搜索,对于两个Bean,类型都相同,这就是问题所在。

要解决此问题,您可以添加@Qualifier以按bean名称解析自动装配。

或者你可以将@Primary添加到其中一个Bean中,如果默认情况下应该使用其中一个。

例如,

@Bean
@Primary
FilterRegistrationBean someFilterRegistration() {
  ...
}
@Bean
FilterRegistrationBean shareFilterRegistration() {
 ...
}

为此,如果你这样做

@Autowired
FilterRegistrationBean bean;

你得到someFilterRegistration()自动装配,并通过

@Autowired
@Qualifier("shareFilterRegistration")
FilterRegistrationBean bean;

你会得到另一个。