【Spring】Spring 可以将接口所实现的类都注入到接口类型的List、Map中

Spring 提供了依赖注入的功能,可以通过注解或者配置来实现将接口的实现类注入到接口类型的 List、Map 中。 @Autowired 是重点!除此之外,@RequiredArgsConstructor 也可以代替他的功能。参考【注解】@RequiredArgsConstructor 按需自动生成构造函数,举例说明

Spring自动扫描组件 : 如果你的项目是一个Spring应用程序,并且使用了组件扫描,Spring容器会自动扫描并创建实现了 MyInterface 接口的类的实例,并将它们注册为Bean。然后,你可以使用@Autowired 或其他依赖注入方式,将这些Bean注入到 MyService 类中的 myInterfaceList 列表中。这样,你无需手动初始化,Spring会帮助你管理这些实现类的对象。

假设有以下接口和实现类:

java 复制代码
public interface MyInterface {
    void doSomething();
}

@Service
public class MyServiceImpl1 implements MyInterface {
    @Override
    public void doSomething() {
        System.out.println("Implementation 1");
    }
}

@Service
public class MyServiceImpl2 implements MyInterface {
    @Override
    public void doSomething() {
        System.out.println("Implementation 2");
    }
}

1、List 注入:

你可以使用 @Autowired 注解结合 List 类型进行注入:

java 复制代码
@Service
public class MyService {
    @Autowired
    private List<MyInterface> myInterfaceList;

    public void executeAll() {
        for (MyInterface myInterface : myInterfaceList) {
            myInterface.doSomething();
        }
    }
}

Spring 会自动将所有实现 MyInterface 接口的类注入到 myInterfaceList 中。

2、Map 注入:

如果想要将实现类按照名称注入到 Map 中,可以使用 Autowired 结合 Map 类型:

java 复制代码
@Service
public class MyService {
    @Autowired
    private Map<String, MyInterface> myInterfaceMap;

    public void execute(String implementationName) {
        MyInterface myInterface = myInterfaceMap.get(implementationName);
        if (myInterface != null) {
            myInterface.doSomething();
        }
    }
}

在这种情况下,实现类的 Bean 名称会作为 Map 的键。

需要确保 Spring 上下文中存在实现接口的实例,可以通过 @Service 或其他适当的注解确保它们被扫描到。

相关推荐
EatFan38 分钟前
Spring Boot 4.0 升级清单:JDK 基线、Jakarta 命名空间、Observation API 与第三方组件兼容一次讲清
java·spring boot·后端
辰海Coding1 小时前
平台如何接入一台物联网设备?又该如何设计它的通信协议?
java·物联网
代码民工正电荷1 小时前
JAVA重要知识点和集合
java·开发语言
李少兄3 小时前
IDEA Apifox Helper 插件踩坑:2.0.15-243 版本“导出指定接口”参数描述丢失问题解析与修复方案
java·ide·intellij-idea
努力攀登的小k3 小时前
《新手练表:从建表到删表全操作|从零学会表操作》
java·数据库·mysql
Yetian_20004 小时前
Postman测试上传图片文件接口
java·postman
爪哇碎碎念4 小时前
【Java】从一次 cache.get(key) 进去:缓存击穿一瞬间打出 200 次 DB,JDK 17 实测三种解法
java·redis·缓存
csdn_aspnet4 小时前
Java 使总距离最短的最佳点位置(Optimum location of point to minimize total distance)
java·算法
源码_空间4 小时前
基于Springboot的在线编程练习判题平台(源码+文档)
java·spring boot·后端
小手cool6 小时前
二分查找:在有序数组中查找最接近 target 的元素索引
java·数据结构·算法