spring特殊注入(List,Map)

今天寫一個(gè)有意思的東西,spring的特殊注入(List,Map)

之前在整理觀察者模式和中介者模式的時(shí)候,都需要有一個(gè)集合容器來放入我們的被執(zhí)行的對象(前文請參考:觀察者,中介者
有時(shí)候不同邏輯需要的集合里面元素不一樣,有時(shí)候會(huì)引出線程安全問題(可以用多例來保證線程安全)。


看看今天需要學(xué)習(xí)的內(nèi)容,首先定義一個(gè)接口和三個(gè)實(shí)現(xiàn)類:

一個(gè)接口和三個(gè)實(shí)現(xiàn)類

需要把這幾個(gè)實(shí)現(xiàn)類放入集合中,方便我們調(diào)用

通常做法:

    @Resource(name = "aDemoService")
    private DemoService aDemoService;

    @Resource(name = "bDemoService")
    private DemoService bDemoService;

    @Resource(name = "cDemoService")
    private DemoService cDemoService;


    @Test
    void test(){
        List<DemoService> demoServices = new ArrayList<DemoService>();
        demoServices.add(aDemoService);
        demoServices.add(bDemoService);
        demoServices.add(cDemoService);

        demoServices.stream()
                .forEach((a) -> {
                    System.out.println(a);
                });
    }

輸出結(jié)果:

com.example.specialinjection.service.ADemoService@5f404594
com.example.specialinjection.service.BDemoService@53692008
com.example.specialinjection.service.CDemoService@7b2a3ff8


今天有個(gè)更加簡單的注入方式,直接注入容器類(List,Map),來滿足我們的需求
no bi bi,show code:

    @Autowired
    private List<DemoService> demoServiceList;

    @Autowired
    private Map<String, DemoService> demoServiceMap;

    @Test
    void contextLoads() {
        demoServiceList.stream()
                .forEach((a) -> {
                    System.out.println(a);
                });

        System.out.println("_______________________________________________");

        demoServiceMap.entrySet().stream()
                .forEach((a) -> {
                    System.out.println(a.getKey());
                    System.out.println(a.getValue());
                });
    }

結(jié)果:

com.example.specialinjection.service.ADemoService@5b3bb1f7
com.example.specialinjection.service.BDemoService@58d6b7b9
com.example.specialinjection.service.CDemoService@3f1a4795
_______________________________________________
aDemoService
com.example.specialinjection.service.ADemoService@5b3bb1f7
bDemoService
com.example.specialinjection.service.BDemoService@58d6b7b9
cDemoService
com.example.specialinjection.service.CDemoService@3f1a4795


是不是很簡單

-如果注入list集合,則元素是該list泛型的所有實(shí)現(xiàn)類(這里的list元素順序,我們可以在springbean上加上@Order控制順序)
-如果注入map集合,則元素key為springbean的名稱,值為該map值泛型的所有實(shí)現(xiàn)類

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容