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

相关推荐
AllenIverrui14 分钟前
MyBatisPlus的使用
spring boot·spring·java-ee·mybatis
空青72618 分钟前
ChatGPT在Java后端开发中的应用与影响
java·开发语言·人工智能·后端·神经网络·机器学习·chatgpt
莫得等待19 分钟前
MySQL的慢sql
java
威哥爱编程31 分钟前
Nginx性能调优5招35式不可不知的策略实战
java·nginx·性能调优
五月阳光暖洋洋41 分钟前
SpringBoot2.2.6使用spring-boot-validation读取不到自定义配置文件中的属性
java·开发语言·spring boot
刘钢筋universe43 分钟前
leetcode hot100
java·算法·leetcode
java66666888844 分钟前
深入理解Spring Boot中的容器与依赖注入
java·spring boot·后端
u0104058361 小时前
Spring Boot中的依赖注入和控制反转
java·spring boot·后端
猫猫爱吃小鱼粮1 小时前
57、Flink 的项目配置概述
java·flink
龙洋静1 小时前
RabbitMq - Java客户端基础【简单案例 +Work模型】
java·rabbitmq·java-rabbitmq