Autowired + Map、 List 实现在一个方法里面实例化同一个接口的多实现类的通用方法
少说废话看代码
Fruit 接口
public interface Fruit {
public String name(String name);
}
Apple实现类
import org.springframework.stereotype.Component;
/**
* @Author Administrator
* @Date 2021/9/24 23:30
*/
@Component(value = "apple")
public class Apple implements Fruit{
@Override
public String name(String name) {
return "苹果";
}
}
Banana实现类
import org.springframework.stereotype.Component;
/**
* @Author Administrator
* @Date 2021/9/24 23:31
*/
@Component(value = "banana")
public class Banana implements Fruit {
@Override
public String name(String name) {
return "香蕉";
}
}
Pear实现类
import org.springframework.stereotype.Component;
/**
* @Author Administrator
* @Date 2021/9/24 23:32
*/
@Component
public class Pear implements Fruit{
@Override
public String name(String name) {
return "梨";
}
}
TestInterfaceController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* @Author Administrator
* @Date 2021/9/24 23:28
*/
@RestController
public class TestInterfaceController {
@Autowired
private Map<String, Fruit> fruitMap;
@Autowired
private List<Fruit> fruitList = Collections.emptyList();
@PostMapping("/testFruit")
public void testFruit(String name) {
Fruit fruit = fruitMap.get(name);
System.out.println(fruitMap);
System.out.println(fruit);
List<Fruit> fruits = fruitList;
System.out.println(fruitList);
for (int i = 0; i < fruits.size(); i++) {
if (fruits.get(i).getClass().getSimpleName().equals("Apple")) {
System.out.println("苹果");
}
if (fruits.get(i).getClass().getSimpleName().equals("Banana")) {
System.out.println("香蕉");
}
if (fruits.get(i).getClass().getSimpleName().equals("Pear")) {
System.out.println("梨");
}
}
}
}
postman测试
debug看结果
可以看到实现了Fruit接口的类确实是都被放到了Map和List中。
这是怎么实现的呢
(1)第一步:在实现了Fruit接口的类添加注解@Component,value参数可加可不加,不加默认为实现类的名称,加上则是以你加上去的为准,而这个value值则会成为Map的key值,而Map的value值则是存放实现类的实例化对象。
需要注意的是,若@Component不加value参数,则map中的key取的值是实现类的名称,但是这个名称会自动以小写开头,就算你原来的实现类名称为大写开头,也会变为小写的。可以看到Pear变成了pear
(2)第二步:在需要用到的地方添加以下语句
@Autowired
private Map<String, Fruit> fruitMap;
@Autowired
private List<Fruit> fruitList = Collections.emptyList();
然后在逻辑中这样使用
Fruit fruit = fruitMap.get(name);
System.out.println(fruitList);
end
这种实现模式似乎叫策略模式,不是很清楚,从公司学来的,网上有关策略模式的可见看文章:基于SpringBoot的策略模式多实现类注入(Map注入)