aku*_*ma8 3 java spring interface spring-data
当我有很多存储库接口时,我通常使用这样的包装器:
@Component
public class RepositoryContainer(){
@Autowired
public Myrepo1 repo1;
@Autowired
public Myrepo2 repo2;
//and so on....
}
Run Code Online (Sandbox Code Playgroud)
然后我用它:
@Service
public class Myservice(){
@Autowired
RepositoryContainer repos;
public void service1(){
repos.repo1.findBy...
}
}
Run Code Online (Sandbox Code Playgroud)
问题是这种做法生成了很多文件,因为每个存储库都是一个接口,所以我有相同的存储库文件和实体.
为了减少我尝试使用嵌套接口的文件数量:
@Repository
public class RepositoryContainer(){
public interface Myrepo1 extends JpaRepository<Entity1, Long> {
}
public interface Myrepo2 extends JpaRepository<Entity2, Long> {
}
//and so on...
}
Run Code Online (Sandbox Code Playgroud)
现在我很努力,因为我无法在课外访问我的存储库.有没有办法做到这一点 :
@Service
public class Myservice(){
@Autowired
RepositoryContainer repos;
public void service1(){
//I would like to do this :
repos.Myrepo1.findBy...
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我已经启用了嵌套发现存储库
@EnableJpaRepositories( considerNestedRepositories = true )
Run Code Online (Sandbox Code Playgroud)
非常感谢
只要打开参数considerNestedRepositories的EnableJpaRepositories注释:
@SpringBootApplication
@EnableJpaRepositories(considerNestedRepositories = true)
public class Application {
//...
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以注入你的'内部'回购:
@Service
public class Myservice(){
@Autowired Myrepo1 myrepo1;
@Autowired Myrepo2 myrepo2;
public void service1() {
myrepo1.findBy...
myrepo2.findBy...
}
}
Run Code Online (Sandbox Code Playgroud)
我认为没有其他变种......
UPDATE
如果目标是拥有一种"清洁代码",我可以提出一种方法:
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(...);
}
}
Run Code Online (Sandbox Code Playgroud)
与@Cepro0讨论后,我的解决方案是:
@Repository
public class RepositoryContainer(){
public interface Myrepo1 extends JpaRepository<Entity1, Long> {
}
public interface Myrepo2 extends JpaRepository<Entity2, Long> {
}
//I am using an inner bean to get my repositories
@Component
public class Container{
@Autowired
public Myrepo1 repo1;
@Autowired
public Myrepo2 repo2;
}
}
Run Code Online (Sandbox Code Playgroud)
然后 :
@Service
public class Myservice(){
@Autowired
RepositoryContainer.Container repos;
public void service1(){
repos.repo1.findBy...
}
}
Run Code Online (Sandbox Code Playgroud)
这非常有效,从今天起,这就是我将继续减少每个存储库接口的文件数量并拥有干净代码的方法,因为有时我们在服务中需要许多存储库,并且必须将它们一一注入。
如果有人发现一些缺点,请告诉我。
| 归档时间: |
|
| 查看次数: |
1068 次 |
| 最近记录: |