在spring-context-indexer中使用@Primary

时间:2019-07-02 18:08:48

标签: java spring spring-annotations

我正在尝试将"huh"添加到项目的库中。但是,在运行集成测试时,我不想使用依赖项(spring-context-indexer)中的Bean,而是使用SystemConfiguration覆盖它以返回@Primary。似乎与spring-context-indexer无关。

这是我的考试

new MockSystemConfiguration()

和CustomTestSpringconfig

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

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

实际的@Configuration @ComponentScan(basePackageClasses = SystemConfiguration.class) public class CustomTestSpringConfig { @Primary @Bean(name = "SystemConfiguration") public SystemConfiguration systemConfiguration() { return new MockSystemConfiguration(); } } 是在另一个已包含SystemConfiguration的jar中定义的。

spring-component-indexer

正在发生的是使用的是真正的@Component("SystemConfiguration") public class SystemConfigurationImpl implements SystemConfiguration { Bean,而不是带有SystemConfiguration注释的Bean。

1 个答案:

答案 0 :(得分:1)

如果是项目的依赖项(并且您将此依赖项导入到您的应用程序中,但您可以控制该依赖项),则可以使用条件声明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