前言:
spring是支持基于接口实现类的直接注入的;
支持注入map,list等集合中,不用做其他的配置,直接注入;
为什么要用这种方式注入bean呢?
使用场景:
适用于一个接口有多个实现类,然后根据不同的参数选择执行不同的实现类,
其实就是策略模式;
Spring 会在启动时,自动查找实现了该接口的 bean,放到这个Map中去。
key为bean的名字,value为 实现了该接口的所有的 bean。
注意:这里只有在map的key为string类型时才有效;
@Autowired 标注作用于 Map 类型时,如果 Map 的 key 为 String 类型,则 Spring 会将容器中所有类型符合 Map 的 value 对应的类型的 Bean 增加进来,用 Bean 的 id 或 name 作为 Map 的 key。
1.接口
public interface IInterfaceService{
// 接口方法
String doSomething(Map param);
}
2.a实现
@Service("aImpl")
public class AService implements IInterfaceService {
@Override
public String doSomething(Map param) {
// a doSomething...
}
}
3.b实现
@Service("bImpl")
public class BService implements IInterfaceService {
@Override
public String doSomething(Map param) {
// b doSomething...
}
}
使用
/**
* @Autowired 注入map
* 这个注解会将所有IInterfaceService的实现都注入在这个iInterfaceServiceMap里面的,只需要通过key取就是了,key值是 @Service("bImpl") 注解里面的value值,写就用写的那个,没写就用实现类首字母小写的取,如:BService->bService
*/
@Autowired
private final Map<String, IInterfaceService> iInterfaceServiceMap = new ConcurrentHashMap<>();
public void invoke(){
// 从map中拿出来aImpl的实现
IInterfaceService aService = iInterfaceServiceMap.get("aImpl");
String aResult = aService.doSomething(param);
// 从map中拿出来bImpl的实现
IInterfaceService bService = iInterfaceServiceMap.get("bImpl");
String bResult = bService .doSomething(param);
}