ConditionalOnMissingBean

ConditionalOnMissingBean

我有一个接口(interface)的两个实现-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'...

如何配置测试类以使其能够运行?

最佳答案

好的,我知道了。

带有值@ConditionalOnMissingBean(KeyStoreService.class)的注释将尝试仅查找具体实例,而KeyStoreService则不是。这样,它什么也找不到。

当我将注解与类型一起使用时,它的工作原理就像一个魅力:@ConditionalOnMissingBean(type = "KeyStoreService")

10-04 11:06