Home > Blockchain >  Java Spring Webflux: issue types MyInterface and org.springframework.data.repository.reactive.Reacti
Java Spring Webflux: issue types MyInterface and org.springframework.data.repository.reactive.Reacti

Time:12-25

Small question regarding Java Spring Webflux and type incompatibility issues please.

I have a very simple Spring Webflux application, where I declare a common interface for all my repositories to save a pojo:

public interface MyInterface {

    Mono<MyPojo> save(MyPojo myPojo);

}

Here are example of a concrete implementation, for instance, Redis:

@Repository("redis")
public class MyRedisRepository implements MyInterface {
    private final ReactiveRedisOperations<String, String> reactiveRedisOperations;

    public MyRedisRepository(ReactiveRedisOperations<String, String> reactiveRedisOperations) {
        this.reactiveRedisOperations = reactiveRedisOperations;
    }

    @Override
    public Mono<MyPojo> save(MyPojo myPojo) {
        return reactiveRedisOperations.opsForValue().set("someKey", "someValue").map(__ -> myPojo);
    }

}

And now an example with Elastic.

@Repository("elastic")
public interface MyElasticRepository extends ReactiveElasticsearchRepository<MyPojo, String>, MyInterface {

}

Please note, the important point is that some are regular classes (like Redis) which needs to implement the save method.

On the other hand, some are interface which implements Reactive___Repository<MyPojo, String> (which already have a save method)

When trying to compile, I am faced with this issue:

types question.MyInterface and org.springframework.data.repository.reactive.ReactiveCrudRepository<question.MyPojo,java.lang.String> are incompatible;

This is a bit strange to me, as my intention is just to have all the repositories under a common MyInterface , with a save method.

May I ask why I am facing this issue, and most of all, how to resolve this (keeping the MyInterface ) please?

Thank you

CodePudding user response:

The return type and parameter type of the save method defined on the two interfaces are different, which makes them incompatible.

The ReactiveCrudRepository that ReactiveElasticsearchRepository extends, specifies that types derived from MyPojo can be passed to and will be returned from the save method.

In your custom interface you limit the passed argument and return type strictly to MyPojo. So the compiler recognizes there is no way to determine which save method is called at runtime and complains.

Try adjusting the return type of your interface to the following and adjusting your implementations:

public interface MyInterface<T extends MyPojo> {
    Mono<T> save(T myPojo);
}
  • Related