java - Spring 数据: how to use repository's inner interfaces outside the outer class?

标签 java spring interface spring-data

当我有很多存储库接口(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 )

非常感谢

最佳答案

只需打开参数considerNestedRepositoriesEnableJpaRepositories注解:

@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/

相关文章:

Java 接口(interface) - 对象到类的类型转换

go - 这个接口(interface)和私有(private)数据类型模式的概念是什么

Java:请求的细粒度锁定?

java - 保持文本检索的正确风格

Java 图形在连续的函数调用中不显示,为什么?

java - 如何获取所有 Controller 和请求映射方法

ios - 自动化不适用于 iOS6

java - 是什么导致 switch 语句中生成的 R.id.xxx 值出现 "constant expression required"错误?

java - 如何通过 Aggregator 的 Java 配置使用组超时?

java - Spring Ws中如何与银行等第三方收发证书?