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

标签 java spring spring-annotations

我正在尝试将 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/

相关文章:

java - Spring 服务名称与接口(interface)名称冲突

java - DBUtil - 返回错误代码、消息或抛出异常

java - 如何在android中开始新的 Activity

java - 在不重启 Tomcat 7 的情况下在 war 部署后更改 xml/property 文件

java - Spring Boot @ConfigurationProperties 到 map 的 map 或(嵌套 map /MultiKeyMap)

java - 面临 Spring AOP 中 Before 建议的问题

spring-boot - 我的@WebMvcTest 测试类如何在 Spring Boot 中使用此 JDBC 身份验证配置进行初始化?

java - 如何将文件位置作为参数作为字符串传递?

java - 如何在谷歌电子表格 API 中复制工作表

java - 如何在 <projectname>/login 之前和 <localhost> :<portnumber> without hardcode? 之后向 spring 项目添加参数