【Autowired自动注入map】

前言:
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);
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值