Java 将@Primary与spring上下文索引器一起使用
我正在尝试将spring上下文索引器添加到我的项目库中。但是,在运行集成测试时,我不希望使用依赖关系SystemConfiguration中的Bean,而是使用@Primary覆盖它以返回新的MockSystemConfiguration。这似乎不适用于spring上下文索引器 这是我的测验Java 将@Primary与spring上下文索引器一起使用,java,spring,spring-annotations,Java,Spring,Spring Annotations,我正在尝试将spring上下文索引器添加到我的项目库中。但是,在运行集成测试时,我不希望使用依赖关系SystemConfiguration中的Bean,而是使用@Primary覆盖它以返回新的MockSystemConfiguration。这似乎不适用于spring上下文索引器 这是我的测验 @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = CustomTestSpringConfig.class) class
@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();
}
}
真正的系统配置是在另一个jar中定义的,该jar中已经有spring组件索引器
实际情况是使用的是真正的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,那么使用测试概要文件运行测试是很自然的,因此您可以使用@Profiletest和@ActiveProfilestest
这里有很好的例子:您是否创建了SystemConfiguration类型的bean?是您的项目的依赖关系还是外部的?使用SystemConfiguration的定义更新了该问题
@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();
}