java - 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,但效果不佳。
解决方案
不确定这是否是此问题的确切解决方案,但是当尝试使用 Java 8 可选类型时,这并没有成功。但是,当我切换到 Spring 时ObjectProvider
,它工作正常。理想情况下,这只是一种解决方法,而不是此问题的根本原因。
推荐阅读
- excel - 自动过滤后将范围设置为表格列,Excel VBA
- python - 如何从张量流中的数据集类中获取 10K MNIST 图像的子集?
- python - 如何不并行运行批处理文件和python?
- javascript - Gulp 安装有效,但 gulp 没有响应
- elasticsearch - 使用文件名和编号进行范围搜索
- performance - Solr:是否可以缓存规模提升功能结果?
- javascript - 检测 TD 可编辑更改并更改 css 颜色
- java - 无法从另一个本机应用程序的 Android 库中选择图像
- javascript - NodeJS Javascript 代码在 Windows 上运行但不在 Linux 上
- python - 为什么 CuDNNLSTM 和 LSTM 在 Keras 中有不同的预测?