日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring@主要注释

發(fā)布時間:2023/12/3 javascript 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring@主要注释 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

介紹:

當存在多個相同類型的bean時,使用Spring @Primary批注為標記的bean提供更高的優(yōu)先級。

默認情況下,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標記為主豆。

在本教程中,我們將更詳細地探討此批注的用法。

假設(shè)我們有以下配置類:

@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。 現(xiàn)在,讓我們啟動我們的應用程序:

AnnotationConfigApplicationContext context =AnnotationConfigApplicationContext(UniversityConfig.class);Person student = context.getBean(Person.class); System.out.println(student.getClass());

我們將看到Spring嘗試自動裝配時,一個Student對象得到了優(yōu)先選擇。

使用

假設(shè)我們啟用了組件掃描:

@Configuration @ComponentScan(basePackages="com.programmergirl.beans") public class UniversityConfig {?? }

對于這種情況, 我們可以使用@Primary直接注釋我們的Spring組件類:

@Primary @Component public class Student implements Person {... }@Component public class Teacher implements Person {... }

現(xiàn)在,當直接嘗試插入不帶@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());...} }

結(jié)論:

在本快速教程中,我們探討了Spring中@Primary批注的用法。

顧名思義,當有多個相同類型的bean時,我們可以使用@Primary批注定義一個主對象。

翻譯自: https://www.javacodegeeks.com/2019/10/spring-primary-annotation.html

總結(jié)

以上是生活随笔為你收集整理的Spring@主要注释的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。