在 java 中显式调用默认方法 - 当实现的接口使用泛型时

Explicitly calling a default method in java - when the implemented interface uses generics

这个问题与 this one 相同,但有所不同。

我有一个界面,例如:

@Repository
public interface InvoiceRepository extends JpaRepository<Invoice, String>{

  // some other methods here 

 default Invoice save(Invoice invoice) {

        //I do sth here

        return JpaRepository.super.save(invoice); // wonT work
    }

}

如何调用已实现的JPA接口的save方法?


更新: 事实上,我注意到,保存在扩展 JPARepository 接口

中不是默认设置

在这种情况下,实现此目标的最佳方法是什么?

您定义的默认方法无能为力,因为 Spring 将开箱即用地实现具有相同擦除的方法(请参阅 CrudRepository.save())。

这里你不调用接口的default方法:

JpaRepository.super.save(invoice); 

您调用了 CrudRepository 的抽象 save() 方法。
但它无法按原样编译 abstract.
如果 JpaRepositorysuper class 定义了默认的 save() 方法,它可以像引用的问题一样工作,但事实并非如此。

In this case, what would be the best way of achieving this ?

您可以创建一个具有不同名称的 default 方法,并从中调用 save(),该方法在运行时将调用运行时 InvoiceRepository 实例:

default Invoice saveInvoice(Invoice invoice) {
    // I do sth here
    ...
    return save(invoice); 
}

在您的情况下,方法 save() 不是 default。从代码中,它定义为:

<S extends T> S save(S var1); // abstract, public

注意 - 也罢,代码属于神器org.springframework.data:spring-data-jpa:2.0.9.RELEASE.

或者如果我可以说,你的推论是不正确的,"default 默认情况下不暗示。"