Wim*_*uwe 7 java spring-data spring-data-jpa
我想扩展一个JpaRepository自定义实现,所以我添加了一个MyRepositoryCustom接口和一个MyRepositoryImpl扩展此接口的类.
有没有办法从JpaRepository我的自定义类中调用方法?
注意:这也是作为对/sf/answers/831684241/的评论而提出的,但我认为值得一个单独的问题是很常见的.
Oli*_*ohm 13
要将核心存储库接口注入自定义实现,Provider<RepositoryInterface>请将a 注入到自定义实现中.
实现这一目标的核心挑战是正确设置依赖注入,因为您要在要扩展的对象和扩展之间创建循环依赖关系.但是,这可以解决如下:
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
}
Run Code Online (Sandbox Code Playgroud)
这里最重要的部分是使用Provider<MyRepository>这将导致Spring创建为依赖一个延迟初始化代理甚至当它创建一个实例MyRepository摆在首位.在自定义方法的实现中,您可以使用….get()-method 访问实际的bean .
Provider是来自@InjectJSR 的接口,因此是标准化接口,需要对该API JAR的额外依赖.如果你只想坚持使用Spring,你可以使用它ObjectFactory作为替代接口但是获得完全相同的行为.
| 归档时间: |
|
| 查看次数: |
1802 次 |
| 最近记录: |