我有一个要在组件扫描时排除的类。我正在使用下面的代码来做到这一点,但这似乎没有用,尽管一切似乎都正确

@ComponentScan(basePackages = { "common", "adapter", "admin"}, excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ServiceImpl.class) })

实际上,我想在我的其余api逻辑中使用实现“Service”接口(interface)的“ServiceImpl”类,并且在进行api的集成测试时,我想排除此实现并加载模拟的实现。但这似乎没有发生,即使使用了上面的我也收到以下错误
No qualifying bean of type [admin.Service] is defined: expected single matching bean but found 2: ServiceMockImpl,ServiceImpl

我花了太多时间在此上,但没有任何效果。

任何帮助表示赞赏。

最佳答案

经过大量的工作和研究,我注意到在组件扫描方面,Spring的行为并不奇怪。

伪像是这样的:
ServiceImpl是真正的实现类,它实现Service接口(interface)。ServiceMockImpl是实现Service接口(interface)的模拟植入类。

我想调整组件扫描,使其仅加载ServiceMockImpl而不加载ServiceImpl

我必须在测试配置类的@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ServiceImpl.class)中添加@ComponentScan,以从组件扫描中排除该特定类。但是即使进行了上述更改,两个类都已加载,并且测试失败。

经过大量的工作和研究,我发现ServiceImpl被加载是因为另一个类正在加载,并且该类顶部的所有软件包都具有@ComponentScan。因此,我添加了将Application类从组件扫描中排除的代码,如下@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Application.class)所示。

之后,它按预期工作。

如下代码

@ComponentScan(
    excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = OAuthCacheServiceImpl.class),
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Application.class)
    },
    basePackages = {
        "common", "adapter", "admin"
    }
)

我已经看到很多有关组件扫描的问题很久没有得到回答,因此我想添加这些详细信息,因为这可能对将来的人们有所帮助。

HTH ...

10-07 20:33