关于java:客户方法的UnsatisfiedDependencyException

UnsatisfiedDependencyException for customer method

在命令行中运行spring boot之后,出现以下错误:https://egkatzioura.com/2016/06/03/add-custom-functionality-to-a-spring-data-repository/

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

此问题正在申请中:

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

服务中的实现为

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

在为method添加了自定义的repo实现后,即使只是为了返回消息而进行了更改,我仍然遇到问题。

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

顺便说一句,此脚本用于探索/学习。


CustomerRepository中实现TransactionRepoCustom

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

因此,Spring尝试找到在TransactionRepoCustom中声明的方法public String getAllTransaction()的实现(但未这样做)。

因此,要解决此问题,您需要:

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

按照第一种方法,它将类似于:

1
2
3
4
5
6
public class TransactionRepoCustomImpl implements TransactionRepoCustom {
    @Override
    public String getAllTransaction() {
        return"logic for your custom implementation here";
    }
}

遵循最后一种方法是:

1
2
3
4
5
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会尝试查找在TransactionRepoCustom中声明的所有方法的实现。由于您未提供任何内容,因此spring无法为您创建该bean。

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

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

当只有一个方法(可争论)时,可以在同一接口中声明一个default实现,但是如果接口变大,则可能很难维护。