[英]How do I use Qualifiers in Spring boot
This is my project structure这是我的项目结构
MODEL MODEL
Repo回购
Controller (uses the TodoRepo for CRUD operations) Controller(使用 TodoRepo 进行 CRUD 操作)
I am a bit confused, how should i go about using qualifiers here?我有点困惑,我应该如何 go 在这里使用限定符? Should I create different Repositories for each type?
我应该为每种类型创建不同的存储库吗?
TodoRepo.java - extends JPA repo with <TodoItem, Integer> TodoRepo.java - 使用 <TodoItem, Integer> 扩展 JPA repo
Here TodoItem is an interface.这里 TodoItem 是一个接口。 Springboot JPA gets confused about which entity it is going to handle(two class implements the TodItem interface).
Springboot JPA 对它要处理哪个实体感到困惑(两个 class 实现了 TodItem 接口)。 Instead of Interface, declaring a specified entity class won't throw the error.
声明指定的实体 class 而不是接口不会引发错误。
I think you need to create two different repositories.我认为您需要创建两个不同的存储库。 And then you can use the @Autowired annotation to inject the desired bean into your controller.
然后您可以使用@Autowired 注释将所需的 bean 注入您的 controller。
This will inject the appropriate repository implementation (TodoType1Repo or TodoType2Repo) into your controller based on the value of the @Qualifier annotation.这将根据 @Qualifier 注释的值将适当的存储库实现(TodoType1Repo 或 TodoType2Repo)注入到您的 controller 中。
more about @Qualifier https://www.baeldung.com/spring-qualifier-annotation更多关于@Qualifier https://www.baeldung.com/spring-qualifier-annotation
@Qualifier("todoType1Repo")
@Repository
public class TodoType1Repo extends JpaRepository<TodoType1, Integer> {}
@Qualifier("todoType2Repo")
@Repository
public class TodoType2Repo extends JpaRepository<TodoType2, Integer> {}
@Autowired
@Qualifier("todoType1Repo")
private TodoRepo todoType1Repo;
@Autowired
@Qualifier("todoType2Repo")
private TodoRepo todoType2Repo;
public void handleRequest1() {
// Use todoType1Repo to perform CRUD operations on TodoType1 objects
}
public void handleRequest2() {
// Use todoType2Repo to perform CRUD operations on TodoType2 objects
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.