2014-08-28 23 views
5

我有一個我想在組件掃描時排除的類。我使用下面的代碼要做到這一點,但似乎並沒有工作,儘管一切都似乎是正確的ComponentScan excludeFilters在Spring 4.0.6.RELEASE中不起作用

@ComponentScan(basePackages = { "common", "adapter", "admin"}, excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ServiceImpl.class) }) 

其實我想有「ServiceImpl」類,它實現了「服務」界面,在使用我的休息API邏輯,並在做一個API的集成測試時,我想排除這種暗示和加載嘲諷的實現。但是,這似乎並沒有我提示以下錯誤:

No qualifying bean of type [admin.Service] is defined: expected single matching bean but found 2: ServiceMockImpl,ServiceImpl 

我花了太多的時間在這,但沒有工作,因爲即使使用上述後發生。

任何幫助表示讚賞。

回答

21

經過大量的工作和研究,我注意到Spring的行爲在組件掃描方面並不奇怪。

文物是這樣的:

「ServiceImpl」纔是真正的實現類,它實現「服務」界面。 「ServiceMockImpl」是實現「服務」接口的模擬植入類。

我想調整組件掃描,以便它只加載「ServiceMockImpl」而不是「ServiceImpl」。

我不得不在測試配置類的「@ComponentScan」中添加「@ ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = ServiceImpl.class)」,以從組件掃描中排除該特定類。但是,即使在做了上述更改並且測試失敗之後,這兩個類都得到了加載。

經過大量的工作和研究後,我發現「ServiceImpl」正在被加載,因爲其他類正在被加載,並且在其上面的所有程序包都有「@ComponentScan」。因此,我添加了代碼以從組件掃描中排除「Application」類,如下所示:「@ ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = Application.class)」。

之後,它按預期工作。

代碼像下面

@ComponentScan(excludeFilters = { 
    @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = OAuthCacheServiceImpl.class), 
    @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Application.class) }, basePackages = { 
    "common", "adapter", "admin"}) 

我已經看到了很多的組件掃描的問題是沒有答案的長,因此我認爲,添加這些細節,因爲它可能有助於在未來的人。

HTH ...

+0

謝謝!它有助於! – zhuguowei 2015-11-30 12:54:36

+2

好主意!這也適用於我: '@ComponentScan(basePackages =「org.package」,excludeFilters = @Filter(classes = {Controller.class,Configuration.class}))' 看起來我們必須明確地告訴Spring跳過配置類。 – Yuriy 2016-01-18 10:36:01

1

首先,非常感謝有關@Yuriy的答案和@ ripudam,但使我困惑是,當我excludeFilters包含Configuration.class我不得不使用@Import導入當我使用excludeFilters = {@Filter(type = FilterType.ANNOTATION,value {EnableWebMvc.class,Controller.class})時,@ Configuration.I註釋到的Classe都運行良好。ContextLoaderListener首先不會註冊Controller 。

例如

//@Import(value = { SecurityConfig.class, MethodSecurityConfig.class, RedisCacheConfig.class, QuartzConfig.class }) 
@ComponentScan(basePackages = { "cn.myself" }, excludeFilters = { 
     @Filter(type = FilterType.ANNOTATION,value={EnableWebMvc.class,Controller.class}) }) 
public class RootConfig { 
} 
0

我使用@Configuration@EnableAutoConfiguration@ComponentScan當試圖排除特定的配置類有一個問題,就是它沒有工作!

最終我通過使用@SpringBootApplication解決了這個問題,根據Spring文檔,它在一個註釋中完成了與上述三個功能相同的功能。

另一個提示是先嚐試不改進包掃描(沒有basePackages過濾器)。

@SpringBootApplication(exclude= {Foo.class}) 
public class MySpringConfiguration {}