组件扫描以避免扫描tst文件夹

时间:2016-05-11 19:28:18

标签: java spring maven junit

我们正在使用spring的组件扫描,并且不希望应用程序上下文加载测试bean(即使它们在相同的路径中定义,即a.b.c)。

MyPackage
    src
        a.b.c.SRC
    tst
        a.b.c.TST

我已经读过,顺序是首先加载src文件夹然后加载测试文件夹。在上面的例子中,如果我组件扫描a.b.c,我只想从SRC加载bean。怎么可能?

2 个答案:

答案 0 :(得分:0)

您可以在组件上使用@Profile(“ProfileName”)注释,当然也可以在执行时设置活动配置文件。组件扫描将忽略与活动配置文件不匹配的bean。 e.g。

@Component
@Profile("production")
public class productionImpl implements SomeInterface{}

@Component
@Profile("test")
public class testImpl implements SomeInterface{}

之后您需要做的就是在实时执行中设置正确的配置文件。您可以将其设置为JVM参数(spring.profiles.active)或将其设置为applicationContext:ApplicationContext.getEnvironment().setActiveProfiles(“ProfileName”);

对于测试执行类,您可以使用@ActiveProfiles(“TestProfileName”)

您可以查看此网站以获取更详细的示例:http://websystique.com/spring/spring-profile-example/

答案 1 :(得分:0)

您可以在上下文配置文件中定义几个类路径扫描的排除过滤器。 aspectj过滤器类型似乎是您想要使用的类型。

<context:component-scan base-package="a.b.c">  
    <context:exclude-filter type="aspectj" expression="a.b.c.TST.*" />  
</context:component-scan>

或者,如果您希望获得更多粒度,可以定义自己的注释并使用annotation排除过滤器类型。

<context:component-scan base-package="com.example">
    <context:exclude-filter type="annotation" expression="path.to.your.package.ScanExclude"/>
</context:component-scan>

这样,所有注释了@ScanExclude注释的类都被有效忽略

相关问题