spring 在Sping Boot 的测试配置文件中加载正确的bean

643ylb08  于 2024-01-05  发布在  Spring
关注(0)|答案(1)|浏览(135)

我的应用程序.yaml有以下条目:

  1. spring:
  2. profiles:
  3. active: test
  4. include: h2, test
  5. key:
  6. enabled: on

字符串
我有以下三个bean定义,并希望在我的测试中加载TestConfig bean。但它在测试中接受NoConfig Bean:

  1. @ConditionalOnProperty(name = "key.enabled", matchIfMissing = true)
  2. @Profile("test")
  3. public class TestConfig {}
  4. @ConditionalOnMissingBean(Config.class)
  5. public class NoConfig {}
  6. @ConditionalOnProperty(name = "key.enabled", matchIfMissing = true)
  7. @Profile("!test")
  8. public class Config{}


我还检查了测试中的活动配置文件,它确实是测试配置文件。

  1. @Value("${spring.profiles.active:Unknown}")
  2. private String activeProfile;

xam8gpfp

xam8gpfp1#

您拥有的Bean NoConfig总是在没有Bean Config时创建。您可以尝试使用@TestConfiguration来定义特定测试所需的Bean,或者您可以编写BeanFactoryPostProcessor以从初始化中排除不必要的Bean
或者尝试在@ConditionalOnProperty注解中添加havingValue属性,并将yaml文件中的key.enabled属性的值设置为true

相关问题