首页 > 解决方案 > 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是存在可选依赖项的根。

标签: javaspringspring-boot

解决方案


AddressHistoryRepository应该在 Spring 上下文中。为此,请在配置中提供将由@ComponentScan. 如果你知道 Spring 有这个定义,你可以@ComponentScan在这个定义所在的包中添加。@Bean另一种方法是使用注释创建自己的定义。


推荐阅读