2016-12-20 42 views
5

如何從組件掃描加載排除一些豆子,在一個方面,從另一個xml,它需要掃描所有包<import>的。 這工作nicly如果我把它主要方面:排除類從測試情境

<context:component-scan base-package="com.main"> 
     <context:exclude-filter expression="com.main.*Controller" type="regex"/> 
</context:component-scan> 

但我需要在生活環境控制器。

我想從我的集成測試的情況下排除控制器類加載。它是如何將有可能實現這一目標?

回答

3

您可以用Spring配置文件是(參考How to set a Spring profile to a package?),通過使用

<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans.xsd 
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-2.5.xsd"> 
     <!-- define profile beans at the end of the configuration file --> 
    <beans profile="test"> 
    <context:component-scan base-package="com.main"> 
      <context:exclude-filter expression="com.main.*Controller" type="regex"/> 
    </context:component-scan> 
    </beans> 

    <beans profile="!test"> 
    <context:component-scan base-package="com.main"/> 
    </beans> 

和註釋您的測試與特定@ActiveProfile("test")

編輯:

如果您的XML沒有定義<component:scan>標籤時,您可以通過使用Java配置控制從單元測試包掃描。

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(loader = AnnotationConfigContextLoader.class) 
public class HelperTest { 

    @Configuration 
    @ComponentScan(basePackages = "yourPackage", 
      excludeFilters = @ComponentScan.Filter(value = Controller.class, type = FilterType.ANNOTATION)) 
    @ImportResource(locations = "classpath:context.xml") 
    static class TestConfiguration { 


    } 
+1

我不希望改變主上下文:如下 的控制器然後可以排除與@ComponentScan excludeFilter。我想說什麼,在可能的話我的測試範圍內排除。 :) –

+0

我的答案更新,讓我知道它是否適合。 –