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

前端 未结 2 1831
慢半拍i
慢半拍i 2020-12-19 05:39

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

2条回答
  •  眼角桃花
    2020-12-19 06:16

    tl;dr

    To inject the core repository interface into a custom implementation, inject a Provider 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, MyRepositoryCustom {
      // Query methods go here
    }
    
    interface MyRepositoryCustom {
      // Custom implementation method declarations go here
    }
    
    class MyRepositoryImpl implements MyRepositoryCustom {
    
      private final Provider repository;
    
      @Autowired
      public MyRepositoryImpl(Provider repository) {
        this.repository = repository;
      }
    
      // Implement custom methods here
    }
    

    The most important part here is using Provider 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.

提交回复
热议问题