java - Spring boot 自动装配外部依赖项以及更多可选依赖项
问题描述
我正在尝试自动装配具有更多可选依赖项的外部服务。
@Autowired
private CustomerService customerService; // external dependency
@GetMapping(value = "/test-cdl2")
public ResponseEntity<List<CustomerLightweightDto>> testCdl2() {
return ResponseEntity.ok(customerService.searchForCustomerAddressByCin("1931454603"));
}
这CustomerService
是一个外部服务。内部CustomerService.searchForCustomerAddressByCin
方法:
@Autowired(required = false)
private AddressHistoryRepository addressRepository; // optional
@Transactional(readOnly = true)
public List<AddressHistoryDto> retrieveAddressHistory(String cin) {
notNull(cin, ERROR_CIN_MISSED.getText());
log.debug("Retrieve list of address history by cin [{}]...", cin);
return addressRepository.findByPartyIdOrderByEndDateDesc(findPartyIdByCin(cin));
}
我们将addressRepository
其定义为可选依赖项。
现在,当我尝试运行时testCdl2
,它会抛出 NPE。我如何告诉 Spring 为嵌套依赖项创建一个 bean?
编辑:已经配置了外部依赖的根包ApplicationConfig
:
@Configuration
@ComponentScan({"com.rbs.fsap.aap.customer.data", "com.rbs.fsap.aap.ldap.security"})
@EnableCaching
@EnableRetry
public class ApplicationConfig {
这com.rbs.fsap.aap.customer.data
是存在可选依赖项的根。
解决方案
AddressHistoryRepository
应该在 Spring 上下文中。为此,请在配置中提供将由@ComponentScan
. 如果你知道 Spring 有这个定义,你可以@ComponentScan
在这个定义所在的包中添加。@Bean
另一种方法是使用注释创建自己的定义。
推荐阅读
- android - Ionic4:绑定无法从外部设备工作
- leaflet - 为什么捕捉在 Leaflet 1.0.0 及更高版本上不起作用?
- google-cloud-data-fusion - 如何在 Data Fusion Studio 中将节点的输出作为属性变量传递给下一个节点
- java - 实现 Pagefactory 和显式等待时出错
- swift - 在 Swift 中的手机启动时运行应用程序
- google-apps-script - 基于 TypeError 触发的函数失败:在对象 FULL 中找不到函数 getMessages
- django - 如何配置 uwsgi + nginx + Django + websocket?
- java - Java 条件循环
- ios - 为什么没有分配相同的闭包类型
- c# - Visual Studio 安装项目创建的 MSI 无法从安装位置运行 exe