注释 @ConditionalOnMissingBean 在测试中不匹配

JiK*_*Kra 5 java spring spring-boot

我有一个接口的两个实现 - 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 {
Run Code Online (Sandbox Code Playgroud)

现在,问题正在测试DevKeyStoreServiceTestDevKeyStoreService。我有这样的配置:

@SpringBootTest(
    classes = {DevKeyStoreService.class},
    properties = {"keystore.file="}
)
@RunWith(SpringRunner.class)
@ActiveProfiles("dev")
public class DevKeyStoreServiceTest {

    @Autowired
    private DevKeyStoreService tested;

    @Test
    public void testPrivateKey() {
    } //... etc.
Run Code Online (Sandbox Code Playgroud)

结果是:

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

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

如何配置测试类才能运行它?

JiK*_*Kra 12

好的,我想通了。

带值的注释@ConditionalOnMissingBean(KeyStoreService.class)试图只找到具体的实例,而KeyStoreService不是哪个接口。这样,它找不到任何东西。

当我使用带有类型的注释时,它就像一个魅力:@ConditionalOnMissingBean(type = "KeyStoreService")

  • 更奇怪的是 - 它也不适用于完全限定的名称。 (3认同)