将 @Primary 与 spring-context-indexer 一起使用

Using @Primary with spring-context-indexer

我正在尝试将 spring-context-indexer 添加到我的项目的库中。但是,当 运行 集成测试时,我不想使用来自依赖项(SystemConfiguration)的 Bean,而是使用 @Primary 覆盖它到 return a new MockSystemConfiguration().这似乎不适用于 spring-context-indexer。

这是我的测试

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = CustomTestSpringConfig.class)
class SpringDataConfigurationTest {

    @Test
    void applicationContextCanStart() {
        assertTrue(true);
    }
}

和 CustomTestSpringconfig

@Configuration
@ComponentScan(basePackageClasses = SystemConfiguration.class)
public class CustomTestSpringConfig {
    @Primary
    @Bean(name = "SystemConfiguration")
    public SystemConfiguration systemConfiguration() {
        return new MockSystemConfiguration();
    }
}

真正的 SystemConfiguration 是在另一个已经包含 spring-component-indexer 的 jar 中定义的。

@Component("SystemConfiguration")
public class SystemConfigurationImpl implements SystemConfiguration {

正在发生的是真正的 SystemConfiguration Bean 而不是用 @Primary 注释的 Bean。

如果它是您项目的依赖项(并且您将此依赖项导入到您的应用程序中,但您可以控制该依赖项),那么声明一个带有条件的 bean 是有意义的。 F.e.:

@Bean
@ConditionalOnMissingBean(SystemConfiguration.class) // mock bean in tests would be of the the same type so this one is skipped
SystemConfiguration systemConfiguration() {
    return new SystemConfigurationImpl();
}

如果您无法控制依赖关系并且需要测试 bean,那么 运行 使用 test 配置文件进行测试是很自然的,因此您可以使用 @Profile("test")@ActiveProfiles("test")

这里有很好的例子:Spring Profiles