您好,登錄后才能下訂單哦!
當通過接口的方式注入Bean時,如果有多個子類的bean存在時,具體哪個bean會被注入呢?系統中能否存在兩個重名的bean呢?如果可以,那么怎么選擇引入呢?如果不行的話又該怎么避免上面的問題呢?
<!-- more -->
I. 多實例Bean的選擇
這個場景可以說是比較常見的,現在提倡面向接口編程嘛,當一個接口有多個實例時,怎么注入和引用就需要我們額外關注下了
一個輸出的接口定義如下
public interface IPrint {
void print(String msg);
}
對應給兩個實現
@Component
public class ConsolePrint implements IPrint {
@Override
public void print(String msg) {
System.out.println("console print: " + msg);
}
}
@Slf4j
@Component
public class LogPrint implements IPrint {
@Override
public void print(String msg) {
log.info("log print: {}", msg);
}
}
下面就是我們一般的引用方式
@Autowired注解時,屬性名即為默認的Bean名,如下面的logPrint就是獲取beanName=logPrint的bean
@Resource(name=xxx) 直接指定Bean的name,來唯一選擇匹配的bean
@Component
public class NormalPrintDemo {
@Resource(name = "consolePrint")
private IPrint consolePrint;
@Autowired
private IPrint logPrint;
@PostConstruct
public void init() {
consolePrint.print(" console print!!!");
logPrint.print(" log print!!!");
}
}
上面是兩種常見的使用姿勢,此外還可以借助@Primary注解來聲明默認的注入bean
根據上面的作用說明,很明顯可以得知一點
@Primary注解的使用有唯一性要求:即對應上面的case,一個接口的子類中,只能有一個實現上有這個注解
假設將這個注解放在LogPrint上之后,如下
@Slf4j
@Component
@Primary
public class LogPrint implements IPrint {
@Override
public void print(String msg) {
log.info("log print: {}", msg);
}
}
結合上面的常用姿勢,加上這個注解之后,我們的測試用例應該至少包含下面幾個
@Resource 指定beanName的是否會被@Primary影響
前面的@Autowired注解 + 屬性名的方式,是按照第一節的方式選擇呢,還是選擇被@Primary標識的實例
@Autowired + 隨意的一個非beanName的屬性,驗證是否會選中@Primary標識的注解
@Component
public class PrintDemoBean {
@Resource(name = "logPrint")
private IPrint print;
/**
* 下面的注解不指定name,則實例為logPrint
*/
@Autowired
private IPrint consolePrint;
// logPrint的選擇,由@Primary注解決定
@Autowired
private IPrint logPrint;
// logPrint的選擇,由@Primary注解決定
@Autowired(required = false)
private IPrint xxxPrint;
@PostConstruct
public void init() {
print.print("expect logPrint for [print]");
consolePrint.print(" expect logPrint for [consolePrint]");
logPrint.print("expect logPrint for [logPrint]");
xxxPrint.print("expect logPrint for [xxxPrint]");
}
}
執行結果如下
2018-10-22 19:42:40.234 INFO 61966 --- [ main] c.g.h.b.b.choose.sameclz.LogPrint : log print: expect logPrint for [print]
2018-10-22 19:42:40.235 INFO 61966 --- [ main] c.g.h.b.b.choose.sameclz.LogPrint : log print: expect consolePrint for [consolePrint]
2018-10-22 19:42:40.235 INFO 61966 --- [ main] c.g.h.b.b.choose.sameclz.LogPrint : log print: expect logPrint for [logPrint]
2018-10-22 19:42:40.235 INFO 61966 --- [ main] c.g.h.b.b.choose.sameclz.LogPrint : log print: expect logPrint for [xxxPrint]
存在@Primary注解時
@Resource注解指定name時,根據name來查找對應的bean@Autowired注解,全部都用@Primary標識的注解
br/>@Autowired注解,全部都用@Primary標識的注解
不存在@Primary注解時
@Resource注解指定name時,根據name來查找對應的bean@Autowired注解時,根據屬性名去查對應的Bean,如果查不到則拋異常;如果查到,那即是它了
br/>@Autowired注解時,根據屬性名去查對應的Bean,如果查不到則拋異常;如果查到,那即是它了
在我們實際的業務開發中,有多個bean名為xxx的異常應該算是比較常見的,也就是說應該不能有兩個bean叫同一個name;但考慮下下面這個場景
A的服務,依賴B和C的服務;而B和C是兩個完全獨立的第三方服務,他們各自都提供了一個beanName=xxxService的bean,對于A而言,Spring容器中就會有BeanName沖突的問題了,而且這種場景,對A而言,也是不可控的啊,這種情況下改怎么辦?
package com.git.hui.boot.beanorder.choose.samename.a;
import org.springframework.stereotype.Component;
/**
Created by @author yihui in 21:32 18/10/22.*/
@Component
br/>*/
@Component
private String text ;
public SameA() {
text = "a sameA!";
}
public void print() {
System.out.println(text);
}
}
package com.git.hui.boot.beanorder.choose.samename.b;
import org.springframework.stereotype.Component;
/**
Created by @author yihui in 21:33 18/10/22.*/
@Component
br/>*/
@Component
private String text;
public SameA() {
text = "B SameA";
}
public void print() {
System.out.println(text);
}
}
接下來測試下引用,是否有問題
package com.git.hui.boot.beanorder.choose.samename;
import com.git.hui.boot.beanorder.choose.samename.a.SameA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
Created by @author yihui in 21:32 18/10/22.*/
@Component
br/>*/
@Component
@Autowired
private SameA sameA;
@PostConstruct
public void init() {
sameA.print();
}
}
執行之后,毫不意外的拋出了異常,堆棧信息如下
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.git.hui.boot.beanorder.Application]; nested exception is org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'sameA' for bean class [com.git.hui.boot.beanorder.choose.samename.b.SameA] conflicts with existing, non-compatible bean definition of same name and class [com.git.hui.boot.beanorder.choose.samename.a.SameA]
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:184) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:316) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:233) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:271) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:91) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:694) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:398) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:330) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1258) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at com.git.hui.boot.beanorder.Application.main(Application.java:15) [classes/:na]
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'sameA' for bean class [com.git.hui.boot.beanorder.choose.samename.b.SameA] conflicts with existing, non-compatible bean definition of same name and class [com.git.hui.boot.beanorder.choose.samename.a.SameA]
at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.checkCandidate(ClassPathBeanDefinitionScanner.java:348) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:286) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.annotation.ComponentScanAnnotationParser.parse(ComponentScanAnnotationParser.java:132) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:288) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:245) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:202) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:170) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
... 12 common frames omitted
@Component("aSameA")
public class SameA {
private String text ;
public SameA() {
text = "a sameA!";
}
public void print() {
System.out.println(text);
}
}
如果完全不可控呢?正如前面說的兩個第三方服務我都得依賴,但是他們有同名的bean,怎么破?
一個解決方法就是排除掉其中一個同名的bean的自動加載,采用主動注冊的方式注冊這個bean
排除自動掃描的bean的方式如下,在啟動類添加注解@ComponentScan并指定其中的excludeFilters屬性
@SpringBootApplication
@ComponentScan(excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SameA.class)})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
然后自定義一個bean的配置類
package com.git.hui.boot.beanorder.choose.samename;
import com.git.hui.boot.beanorder.choose.samename.a.SameA;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Created by @author yihui in 22:14 18/10/22.
*/
@Configuration
public class AutoConfig {
@Bean
public SameA mySameA() {
return new SameA();
}
}
其他的代碼和之前沒有區別,再次執行,結果如下, 最后的輸出為 a sameA!,根據類型來選擇了實例化的bean了
覺得不錯請點贊支持,歡迎留言或進我的個人群855801563領取【架構資料專題目合集90期】、【BATJTMD大廠JAVA面試真題1000+】,本群專用于學習交流技術、分享面試機會,拒絕廣告,我也會在群內不定期答題、探討。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。