【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 或其他适当的注解确保它们被扫描到。

相关推荐
wasp5201 分钟前
Spring AI 代码分析(十)--Spring Boot集成
人工智能·spring boot·spring
unclecss10 分钟前
把 Spring Boot 的启动时间从 3 秒打到 30 毫秒,内存砍掉 80%,让 Java 在 Serverless 时代横着走
java·jvm·spring boot·serverless·graalvm
tuokuac15 分钟前
@PathVariable与@RequestParam
java·spring
q***160821 分钟前
Tomcat的server.xml配置详解
xml·java·tomcat
程序员西西22 分钟前
SpringBoot整合Apache Spark实现一个简单的数据分析功能
java·后端
n***840722 分钟前
Tomcat 乱码问题彻底解决
java·tomcat
LiLiYuan.25 分钟前
【Lombok库常用注解】
java·开发语言·python
培风图南以星河揽胜1 小时前
Java实习模拟面试|离散数学|概率论|金融英语|数据库实战|职业规划|期末冲刺|今日本科计科要闻速递:技术分享与学习指南
java·面试·概率论
能鈺CMS1 小时前
能鈺CMS · 虚拟发货源码
java·大数据·数据库
sheji34161 小时前
【开题答辩全过程】以 环保监督管理系统为例,包含答辩的问题和答案
java·eclipse