【问题标题】:How to exclude @Configuration class from component-scan in testContext.xml如何从 testContext.xml 中的组件扫描中排除 @Configuration 类
【发布时间】:2017-05-23 12:25:09
【问题描述】:

我有一个用 @Configuration 注释的 AppConfig 类,它有各种 bean 定义,其中包括执行来自应用程序的第三方命中的 bean。现在在我的 spring 集成测试用例中,我不希望这些 bean 被初始化。这就是我创建另一个名称为 TestAppConfig 的 bean 并用 @Configuration 注释的地方,我在其中模拟了所有执行第三方命中的 bean。现在在我的 testContext.xml 中,我正在向 context:component-scan 添加一个排除过滤器,我在其中指定要排除的 AppConfig 包。但不知何故,这个 AppConfig 每次都被初始化。我已经尝试过正确的正则表达式,但仍然无法正常工作。如果有人知道原因,请分享。

【问题讨论】:

  • 使用@Profile@Conditional
  • 不幸的是我不能使用@Conditional,因为我使用的是spring 3.2.16
  • 显示您的配置以及如何启动应用程序。
  • 您可以在 TestAppConfig 类中使用 @Order(1) 来选择测试配置而不是其他配置。

标签: java spring


【解决方案1】:

看到你正在使用spring 3.2的评论后,你可以看到here for old version of spring to use @Profile

您可以使用@Profile 注解来确定将创建或不创建哪个@Bean。

例子:

定义的Bean如下

@Bean
@Profile("production")
    public DataSource prodDataSource() {
        ...
        return dataSource;
    }

@Bean
@Profile("development")
    public DataSource devDataSource() {
        ...
        return dataSource;
    }

对于名为“开发”的配置文件

  1. 在 app.properties spring.profiles.active=development
  2. prodDataSource 不会被调用。但是devDataSource会被调用

对于名为“生产”的配置文件

  1. 在 app.properties spring.profiles.active=production
  2. prodDataSource 不会被调用。但是devDataSource会被调用

【讨论】:

  • 使用@profile 对我有用。这就是我如何解决我的问题。用@profile("test") 注释了我的testAppConfig,并在其各自的测试基础设施设置中添加了@activeProfiles("test")。并用 @profile("!test") 注释了我的 AppConfig。这样,当我的应用启动时,即使我没有明确传递任何配置文件,它也只是检查当前配置文件是否未测试,因此会选择配置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
  • 2013-07-08
  • 2017-07-03
  • 2017-04-24
  • 2016-08-13
  • 1970-01-01
相关资源
最近更新 更多