javaspringspring-bootgenericsfunctional-interface

How can I pass a method into a functional interface for a retry and have it be generic?


I want to a create a functional interface or default method where I pass in a jpa repository method such as findById or findByNumber and have it return a generic type; this way I annotate it with @Retryable if the application fails to connect to db. Below are examples of methods I want passed through the functional interface:

Employee employee = repository.findById("2ed21");
Record record = repository.findbyNumber(311);

Solution

  • How about a simple method with a Supplier as a parameter where you can put literally anything?

    @Retryable(...)
    public <T> T retry(Supplier<T> supplier) {
        return supplier.get();
    }
    

    Usage:

    Employee employee = retry(() -> repository.findById("2ed21"));
    Record record = retry(() -> repository.findbyNumber(311));
    

    Few notes: