Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
891 views
in Technique[技术] by (71.8m points)

java - How to reference the 'normal' spring data repo from a custom implementation?

I want to extend a JpaRepository with a custom implementation, so i add a MyRepositoryCustom interface and a MyRepositoryImpl class extending this interface.

Is there a way to call methods from JpaRepository inside my custom class?

Note: This was also asked as a comment on https://stackoverflow.com/a/11881203/40064, but I think it is common enough to deserve a separate question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

tl;dr

To inject the core repository interface into a custom implementation, inject a Provider<RepositoryInterface> into the custom implementation.

Details

The core challenge to get that working is setting up the dependency injection correctly as you are about to create a cyclic dependency between the object you're about to extend and the extension. However this can be solved as follows:

interface MyRepository extends Repository<DomainType, Long>, MyRepositoryCustom {
  // Query methods go here
}

interface MyRepositoryCustom {
  // Custom implementation method declarations go here
}

class MyRepositoryImpl implements MyRepositoryCustom {

  private final Provider<MyRepository> repository;

  @Autowired
  public MyRepositoryImpl(Provider<MyRepository> repository) {
    this.repository = repository;
  }

  // Implement custom methods here
}

The most important part here is using Provider<MyRepository> which will cause Spring to create a lazily-initialized proxy for that dependency even while it's creating an instance for MyRepository in the first place. Inside the implementation of your custom methods you can then access the actual bean using the ….get()-method.

Provider is an interface from the @Inject JSR and thus a standardized interface and requires an additional dependency to that API JAR. If you want to stick to Spring only, you can used ObjectFactory as an alternative interface but get the very same behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...