周凯,个人博客

  • 前端
  • 嵌入式
  • 工具
  • 后端
  • 随笔
个人记录
  1. 首页
  2. 后端
  3. java
  4. 正文

@Autowired自动注入map

2023年 6月 28日 579点热度 0人点赞 0条评论

前言

  • spring是支持基于接口实现类的直接注入的;

  • 支持注入map,list等集合中,不用做其他的配置,直接注入;

  • 为什么要用这种方式注入bean呢?

    • 适用于一个接口有多个实现类,然后根据不同的参数选择执行不同的实现类,其实就是策略模式
  • Spring 会在启动时,自动查找实现了该接口的 bean,放到这个Map中去。key为bean的名字,value为 实现了该接口的所有的 bean。

    • 注意:这里只有在map的key为string类型时才有效
    • @Autowired 标注作用于 Map 类型时,如果 Map 的 key 为 String 类型,则 Spring 会将容器中所有类型符合 Map 的 value 对应的类型的 Bean 增加进来,用 Bean 的 id 或 name 作为 Map 的 key。

代码实现

  • 首先定义一个的接口:

    package com.example.demo01.model;
    
    public interface ITest {
      String hello();
    }
  • 这个接口有多个实现类:

@Component("test1")
public class Test1 implements  ITest {
    @Override
    public String hello() {
        return "test1";
    }
}

@Component("test2")
public class Test2 implements  ITest {
    @Override
    public String hello() {
        return "test2";
    }
}

@Component("test3")
public class Test3 implements  ITest {
    @Override
    public String hello() {
        return "test3";
    }
}
  • 这里有三个实现类,都实现了ITest接口

  • 将这三个实现类注入到sping容器中:

    package com.example.demo01;
    
    import com.example.demo01.model.ITest;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    import java.util.Map;
    
    @SpringBootTest
    class Demo01ApplicationTests {
      @Autowired
      Map testMap;
    
      @Test
      void contextLoads() {
      }
    
      @Test
      void testMapAutowired() {
          ITest test1 = testMap.get("test1");
          System.out.println(test1.hello());
          ITest test2 = testMap.get("test2");
          System.out.println(test2.hello());
          ITest test3 = testMap.get("test3");
          System.out.println(test3.hello());
      }
    }
  • 执行如下

代码

  • github地址:test-demo/test-java/mapAutowired/demo01 at main · EightDoor/test-demo · GitHub

🎯 拓展阅读提示

本文涉及的内容已同步至公众号后台,我会在那里分享更多深度内容和实用技巧

→ 点击关注:一行梦境

公众号二维码
本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:2023年 6月 28日

周凯

这个人很懒,什么都没留下

打赏 点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2022-现在 周凯,个人博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蒙ICP备18004897号