W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
前面我們講了很多依賴(lài)注入的功能都是基于注解實(shí)現(xiàn),現(xiàn)在我們回歸原始在這一小節(jié),專(zhuān)門(mén)講解如何通過(guò)代碼形式完成依賴(lài)注入的配置。
在開(kāi)始之前我們先把場(chǎng)景列出來(lái)?,F(xiàn)在我們有一個(gè) “OrderManager” 類(lèi),它在初始化時(shí)會(huì)根據(jù)一些業(yè)務(wù)邏輯來(lái)決定注入的細(xì)節(jié)。例如:具體使用哪一套庫(kù)存系統(tǒng)。
這個(gè)時(shí)候前面講到的各種依賴(lài)注入方式,可能都因?yàn)闆](méi)有太多的靈活性而導(dǎo)致無(wú)法完成場(chǎng)景需要。這個(gè)時(shí)候你可以通過(guò) Hasor 的 InjectMembers
接口完成更加靈活的對(duì)象依賴(lài)注入控制。
具體請(qǐng)看代碼:
public class OrderManager implements InjectMembers {
@Inject // <-因?yàn)閷?shí)現(xiàn)了InjectMembers接口,因此@Inject注解將會(huì)失效。
public StockManager stockBeanTest;
public StockManager stockBean;
//
public void doInject(AppContext appContext) throws Throwable {
boolean useCaseA = ...
if (useCaseA){
this.iocBean = appContext.findBindingBean(
"caseA",PojoBean.class);
}else{
this.iocBean = appContext.findBindingBean(
"caseB",PojoBean.class);
}
//
}
}
您要注意的是,為了避免 InjectMembers 接口注入和注解注入同時(shí)生效造成的混亂。一旦您打算使用 InjectMembers 方式進(jìn)行注入 Hasor 就不會(huì)在解析注解進(jìn)行注入。
接下來(lái)我們?cè)诮榻B一種代碼形式的依賴(lài)注入,還是以上面的例子為樣本。我們可以在 Module 中進(jìn)行預(yù)先配置。
public class OrderManager {
public StockManager stockBean;
...
}
實(shí)現(xiàn)注入的 Module 這樣編寫(xiě):
public class MyModule implements Module {
public void loadModule(ApiBinder apiBinder) throws Throwable {
...
boolean useCaseA = ...;
BindInfo<StockManager> injectTo = null;
if (useCaseA){
injectTo = apiBinder.bindType(StockManager.class)
.to(StockManagerCaseA.class).toInfo();
}else{
injectTo = apiBinder.bindType(StockManager.class)
.to(StockManagerCaseB.class).toInfo();
}
apiBinder.bindType(OrderManager.class).inject("stockBean",injectTo);
}
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: