代码之家  ›  专栏  ›  技术社区  ›  JiKra

注释@ConditionalOnMissingBean在测试中不匹配

  •  1
  • JiKra  · 技术社区  · 7 年前

    我有一个接口的两个实现——default和dev @ConditionalOnProperty 用于默认实现和 @Profile 和 @ConditionalOnMissingBean

    @Service
    @ConditionalOnProperty(prefix = "keystore", value = "file")
    public class DefaultKeyStoreService implements KeyStoreService {
    
    @Service
    @Profile("dev")
    @ConditionalOnMissingBean(KeyStoreService.class)
    public class DevKeyStoreService implements KeyStoreService {
    

    现在,问题正在测试中 DevKeyStoreServiceTest DevKeyStoreService .

    @SpringBootTest(
        classes = {DevKeyStoreService.class},
        properties = {"keystore.file="}
    )
    @RunWith(SpringRunner.class)
    @ActiveProfiles("dev")
    public class DevKeyStoreServiceTest {
    
        @Autowired
        private DevKeyStoreService tested;
    
        @Test
        public void testPrivateKey() {
        } //... etc.
    

    Negative matches:
    -----------------
    DevKeyStoreService:
       Did not match:
          - @ConditionalOnMissingBean (types: service.crypto.KeyStoreService; SearchStrategy: all) found bean 'devKeyStoreService' (OnBeanCondition)
    

    典型的 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'service.crypto.DevKeyStoreServiceTest'...

    2 回复  |  直到 7 年前
        1
  •  12
  •   JiKra    7 年前

    好的,我知道了。

    带值注释 @ConditionalOnMissingBean(KeyStoreService.class) 尝试仅查找具体实例,该实例包含 KeyStoreService 事实并非如此。这样,它什么也找不到。

    当我将注释与类型一起使用时,它就像一个符咒: @ConditionalOnMissingBean(type = "KeyStoreService") .

        2
  •  2
  •   Michael Wiles    7 年前

    现在的问题是,条件是find本身,而不是缺少的bean defaultkeystemreservice。

    如果你这样做

    @ConditionalOnMissingBean(name="defaultKeyStoreService")
    

    另一个选项是专门有一个prod概要文件来启用prodbean。

    有趣的是,如果您使用xml创建这些bean,那么您可以在拥有概要文件时覆盖这些bean。

    <bean id="x" class="X"/>
    

    然后有

    <beans profile="dev">
      <bean id="x" class="Y"/>
    </beans>
    

    当您启用dev概要文件时,它将用dev概要文件中的bean x替换未归档上下文中的x bean。

    但是,使用注释时不会出现相同的行为。

    当个人资料出来的时候,我记录了一个 bug 在这方面,它没有被采纳。