首页 > 解决方案 > Spring Boot 在运行测试时不允许可选 Bean 是惰性的

问题描述

在我的 Spring Boot 2.1 应用程序中,我有一个如下所示的服务类:

@Service
public class AImpl implements A {
    @Autowired
    B bservice;
}

然后自动装配的服务 B 看起来像这样:

@Service
public class BImpl implements B {
    @Autowired(required = false)
    @Lazy
    org.springframework.web.client.RestOperations restTemplate;
}

在我的测试课上:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {...})
@DataJpaTest
@EnableJpaRepositories("com.xxx")
@EntityScan("com.xxx")
public class CImplTest {
    @Autowired
    B bservice;
    @Autowired
    A aservice;
}

运行测试时,我收到以下错误消息:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.client.RestOperations' available: Optional dependency not present for lazy injection point

但是,在运行应用程序时,我没有遇到这个问题并且运行良好。

注意:我尝试用 Java 8 Optional 替换 rstTemplate Autowiring,但效果不佳。

标签: javaspring-boot

解决方案


不确定这是否是此问题的确切解决方案,但是当尝试使用 Java 8 可选类型时,这并没有成功。但是,当我切换到 Spring 时ObjectProvider,它工作正常。理想情况下,这只是一种解决方法,而不是此问题的根本原因。


推荐阅读