实现类:
有一个接口A
public interface A {
//TODO
}
三个实现接口的类B、C和D,其中D没有注释@Component
@Component
public class B implements A {
}
@Component
public class C implements A {
}
public class D implements A {
}
我们通过一个测试类来获得接口A的实现类:
@Component
public class test {
private final Map<String, A> strategyMap = new HashMap<>();
//此时这个map的key是实现类的名字(驼峰命名法),value是实现类
//需要通过构造器来进行
test(Map<String,A> map){
this.strategyMap.clear();
map.forEach((k, v)-> this.strategyMap.put(k, v));
}
public void t(){
Iterator it = strategyMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
System.out.println("key:" + key);
}
}
}
通过方法t()获得map的内容:
key:b
key:c
因为D类没有@Component,所以我们的map中获得不到
继承类同理:
有一个类A
public class A {
//TODO
}
三个继承A类的类B、C和D,其中D没有注释@Component
@Component
public class B extends A {
}
@Component
public class C extends A {
}
public class D extends A {
}
@Component
public class test {
private final Map<String, A> strategyMap = new HashMap<>();
//此时这个map的key是实现类的名字(驼峰命名法),value是实现类
//需要通过构造器来进行
test(Map<String,A> map){
this.strategyMap.clear();
map.forEach((k, v)-> this.strategyMap.put(k, v));
}
public void t(){
Iterator it = strategyMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
System.out.println("key:" + key);
}
}
}
通过方法t()获得map的内容:
key:b
key:c