javascript
spring 注释_Spring@主要注释
spring 注釋
介紹:
當存在多個相同類型的bean時,使用Spring @Primary批注為標記的bean提供更高的優先級。
默認情況下,Spring按類型自動連線。 因此,當Spring嘗試自動裝配并且有多個相同類型的bean時,我們將得到一個NoUniqueBeanDefinitionException :
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.programmergirl.Person]is defined: expected single matching bean but found 2: student, teacher ...為了解決這個問題,我們可以選擇使用Spring @Primary批注,從而將一個bean標記為主豆。
在本教程中,我們將更詳細地探討此批注的用法。
假設我們有以下配置類:
@Configuration public class UniversityConfig {@Bean@Primarypublic Person student() {return new Student();}@Beanpublic Person teacher() {return new Teacher();} }Teacher和Student Bean都繼承自Person ,因此我們將其標記為兩個@Bean注釋方法的返回類型。
但是,請注意, 我們已使用@Primary批注將Student bean標記為主要bean。 現在,讓我們啟動我們的應用程序:
AnnotationConfigApplicationContext context =AnnotationConfigApplicationContext(UniversityConfig.class);Person student = context.getBean(Person.class); System.out.println(student.getClass());我們將看到Spring嘗試自動裝配時,一個Student對象得到了優先選擇。
使用
假設我們啟用了組件掃描:
@Configuration @ComponentScan(basePackages="com.programmergirl.beans") public class UniversityConfig {?? }對于這種情況, 我們可以使用@Primary直接注釋我們的Spring組件類:
@Primary @Component public class Student implements Person {... }@Component public class Teacher implements Person {... }現在,當直接嘗試插入不帶@Qualifier的Person類型時,將插入Student bean:
@Service public class StudentService {// Student bean is primary and so it'll get injected@Autowiredprivate Person student;public void printStudentDetails() {System.out.println(student.getClass());...} }結論:
在本快速教程中,我們探討了Spring中@Primary批注的用法。
顧名思義,當有多個相同類型的bean時,可以使用@Primary批注定義一個主對象。
翻譯自: https://www.javacodegeeks.com/2019/10/spring-primary-annotation.html
spring 注釋
總結
以上是生活随笔為你收集整理的spring 注释_Spring@主要注释的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: (simcity安卓版)
- 下一篇: 套接字linux(套接字 linux)
