客户方法的 UnsatisfiedDependencyException

UnsatisfiedDependencyException for customer method

我在 运行 spring 启动后在命令行中出现错误,如下所示:https://egkatzioura.com/2016/06/03/add-custom-functionality-to-a-spring-data-repository/

我的项目源码在github:https://github.com/b3nhysteria/exprole_spring

问题出在应用程序上:

System.out.println("============"+customerService.getListTransactionByCustomer());

服务中的实现是

public String getListTransactionByCustomer (){
    return customerRepository.getAllTransaction();
}

为方法添加自定义回购 + 实现后,即使仅更改 return 消息,我仍然遇到问题。

如果有人有相同的建议,我会试试

顺便说一句,这个脚本是用来探索/学习的。

CustomerRepository 中扩展 TransactionRepoCustom

public interface CustomerRepository extends JpaRepository<Customer, CustomerId>, TransactionRepoCustom {
    // ...
}

因此,Spring 试图找到 TransactionRepoCustom 中声明的方法 public String getAllTransaction() 的实现(但没有找到)。

要解决此问题,您需要:

  • 实施getAllTransaction;也许创建另一个 class TransactionRepoCustomImpl(推荐!),或
  • 在接口中声明 getAllTransaction 的默认实现(如果您使用 Java 8)。

按照第一种方法,它会是这样的:

public class TransactionRepoCustomImpl implements TransactionRepoCustom {
    @Override
    public String getAllTransaction() {
        return "logic for your custom implementation here";
    }
}

按照最后一种方法,它将是:

public interface TransactionRepoCustom {
    public default String getAllTransaction() {
        return "Not implemented yet!"; // of course, this is just a naive implementation to state my point
    }
}

补充说明:

发生这种情况是因为 Spring 使用其 implements 接口提供的 CustomerRepository 的幕后默认(方法)实现。例如,Jparepository 接口就是这种情况:您可以使用 customerRepository.findAll(),并且您没有在 CustomerRepository 中声明(也没有实现)该方法(它取自Jparepository 的实现,很可能是在依赖项中为您打包的)。

现在,当您创建自己的接口 (TransactionRepoCustom) 并由 CustomerRepository 实现它时,Spring 会尝试找到在 [=14= 中声明的所有方法的实现].由于您没有提供任何内容,spring 无法为您创建该 bean。

在这种情况下,我提供的修复程序 Spring 找到该方法的实现,因此它可以为您创建 bean。

最后,我说建议是为该方法提供一个实现,因为在 Spring 中做事的方式是在接口中声明方法并在其他 class 中提供它们的实现es(该接口的默认实现)。在这种情况下,您可以为此创建一个单独的 class 或在 CustomerRepository.

中实现 getAllTransaction 方法

当只有一种方法(有争议)时,可以在同一接口中声明一个 default 实现,但如果接口增长,则可能难以维护。