如何将一个接口所有的实现类一次性注入(list注入方式)
上级接口: 首先需要定义一个上级接口
public interface Fruit {
void getName();
}
创建三个实现类
实现类一:Apple
import com.myplus.common.Fruit;
import org.springframework.stereotype.Component;
@Component
public class Apple implements Fruit {
public void getName() {
System.out.println("这是一个苹果");
}
}
实现类二:Banana
import com.myplus.common.Fruit;
import org.springframework.stereotype.Component;
@Component
public class Banana implements Fruit {
public void getName() {
System.out.println("这是一个香蕉");
}
}
实现类三:Orange
import com.myplus.common.Fruit;
import org.springframework.stereotype.Component;
@Component
public class Orange implements Fruit {
public void getName() {
System.out.println("这是一个橘子");
}
}
此时,如果我们想要将上述三个组件同时注入到其他spring组件当中,或者说将Fruit接口所有的实现类同时注入,我们当然也可以逐个的进行@Autowired,但是如果Fruit接口后期又有了新的实现类,又需要重新写@Autowired进行注入,这样就显得麻烦,因此,可以使用List方式进行注入。
注入组件
import com.myplus.common.Fruit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class FruitGroup {
@Autowired
List<Fruit> fruits;
@RequestMapping("getBean")
public void beanList() {
for (Fruit fruit : fruits){
fruit.getName();
}
}
}
这里我们使用遍历的方式打印三个组件的属性,查看是否注入成功;
注意:这里采用postman方式进行请求。
验证结果
从打印的结果来看,所有Fruit接口实现类都被注入到Spring容器当中;
拓展:后期如果新增实现类的话也将一并注入FruitGroup当中。