当我有很多存储库接口(interface)时,我通常使用这样的包装器:
@Component
public class RepositoryContainer(){
@Autowired
public Myrepo1 repo1;
@Autowired
public Myrepo2 repo2;
//and so on....
}
然后我使用它:
@Service
public class Myservice(){
@Autowired
RepositoryContainer repos;
public void service1(){
repos.repo1.findBy...
}
}
问题是这种方式会生成许多文件,因为每个存储库都是一个接口(interface),所以我的存储库文件与实体文件相同。
为了减少我尝试使用嵌套接口(interface)的文件数量:
@Repository
public class RepositoryContainer(){
public interface Myrepo1 extends JpaRepository<Entity1, Long> {
}
public interface Myrepo2 extends JpaRepository<Entity2, Long> {
}
//and so on...
}
现在我很挣扎,因为我无法在类外访问我的存储库。
有没有办法做到这一点 :
@Service
public class Myservice(){
@Autowired
RepositoryContainer repos;
public void service1(){
//I would like to do this :
repos.Myrepo1.findBy...
}
}
请注意,我已经在
@EnableJpaRepositories( considerNestedRepositories = true )
非常感谢
最佳答案
只需打开参数considerNestedRepositories
在 EnableJpaRepositories
注解:
@SpringBootApplication
@EnableJpaRepositories(considerNestedRepositories = true)
public class Application {
//...
}
然后您将能够注入(inject)您的“内部” repo :
@Service
public class Myservice(){
@Autowired Myrepo1 myrepo1;
@Autowired Myrepo2 myrepo2;
public void service1() {
myrepo1.findBy...
myrepo2.findBy...
}
}
我认为没有其他变种...
更新
如果目标是拥有一种“干净的代码”,我可以提出一种方法:
public interface MyRepo1 extends JpaRepository<Entity1, Long> {
}
public interface MyRepo2 extends JpaRepository<Entity2, Long> {
}
@Getter
@RequiredArgsConstructor
@Component
public class RepoContainer {
private final MyRepo1 myRepo1;
private final MyRepo2 myRepo2;
}
@RequiredArgsConstructor
@Service
public class MyService() {
private final RepoContainer repoContainer;
public void method() {
repoContainer.getMyRepo1().findBy(...);
repoContainer.getMyRepo2().findBy(...);
}
}
关于java - Spring 数据: how to use repository's inner interfaces outside the outer class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46197070/