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