【问题标题】:Component scan to avoid scanning tst folder组件扫描避免扫描 tst 文件夹
【发布时间】:2016-05-11 19:28:18
【问题描述】:

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

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

我读过这个顺序是先加载 src 文件夹,然后再加载 test 文件夹。在上述情况下,如果我对 a.b.c 进行组件扫描,我只想从 SRC 加载 bean。这怎么可能?

【问题讨论】:

  • 为什么不使用<context:component-scan base-package="a.b.c.SRC" />
  • 因为 a.b.c 中有多个配置类,必须显式导入。
  • 可以说最好的选择是根本没有任何仅用于测试的 Spring 组件。
  • 我同意@kryger 所说的话。 “不希望应用程序上下文加载测试 bean”有点令人困惑。您是否在应用程序启动期间加载包含测试 bean 的应用程序上下文?如果是这种情况,那么它的做法是错误的,您可能需要重构应用程序上下文 xml 文件或配置文件。

标签: java spring maven junit


【解决方案1】:

您可以在组件上使用@Profile("ProfileName") 注释,当然还可以在执行时设置活动配置文件。组件扫描将忽略与活动配置文件不匹配的 bean。例如

@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/

【讨论】:

    【解决方案2】:

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

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

    或者,如果您想要更详细一点,您可以定义自己的注释并使用annotation exclude-filter 类型。

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

    这样,所有使用@ScanExclude注解的类都会被有效地忽略

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-21
      • 2016-01-24
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多