我正在尝试将 spring-context-indexer
添加到我的项目的库中。但是,在运行集成测试时,我不想使用依赖项 (SystemConfiguration
) 中的 Bean,而是使用 @Primary
覆盖它以返回 新的 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
是在一个不同的jar中定义的,其中已经有spring-component-indexer
。
@Component("SystemConfiguration")
public class SystemConfigurationImpl implements SystemConfiguration {
所发生的情况是使用真正的SystemConfiguration
Bean,而不是用@Primary
注释的Bean。
最佳答案
如果它是您的项目的依赖项(并且您将此依赖项导入到您的应用程序中,但您可以控制该依赖项),则声明带有条件的 bean 是有意义的。例如:
@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
关于java - 将 @Primary 与 spring-context-indexer 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56857988/