【springboot】spring注入集合(list,set,map)--策略类

今天在写策略模式,一开始打算使用反射的方式获取策略类,突然想到可不可以借用spring的ioc,使用自动注入的方式.

策略接口
/**
 * 提现策略接口
 *
 * @since 2021-11-11 10:03
 */
public interface WithdrawStrategy {

	/**
	 * 获取当前提现类型标识
	 *
	 * @return 提现类型标识
	 * @since 2021/11/11 10:36
	 */
	int getType();

	/**
	 * 订单结算
	 *
	 * @param orderIds 订单id
	 * @since 2021/11/11 10:09
	 */
	void settlement(String[] orderIds);

}
策略类
/**
 * 支付宝结算
 *
 * @since 2021-11-11 10:10
 */
@Component
public class AlipayPaymentStrategy implements WithdrawStrategy {

	/**
	 * 获取当前提现类型标识
	 *
	 * @return 提现类型标识
	 * @since 2021/11/11 10:36
	 */
	@Override
	public int getType() {
		return 2;
	}

	/**
	 * 订单结算
	 *
	 * @param orderIds 订单id
	 * @since 2021/11/11 10:09
	 */
	@Override
	public void settlement(String[] orderIds) {
		//todo: 进行结算
	}

}

一共有三个策略类 就不一一展示了
在这里插入图片描述

策略上下文
/**
 * 提现上下文
 *
 * @since 2021-11-11 10:13
 */
@Component
public class WithdrawContext {
	/**
	* 注入到策略接口集合
	*/
	@Resource
	private List<WithdrawStrategy> strategy;

	private static Map<Integer, WithdrawStrategy> strategyMap;

	/**
	*将集合转换到map 方便过去具体的策略类
	*/
	@PostConstruct
	public void init() {
		System.err.println(strategy);
		strategyMap = strategy.stream().collect(Collectors.toMap(WithdrawStrategy::getType, a -> a));
	}
	/**
	* 根据类型获取策略类		
	*/
	public static WithdrawStrategy getInstance(Integer type) {
		return strategyMap.get(type);
	}

}

init方法中 打印List<WithdrawStrategy> strategy 发现spring自动将WithdrawStrategy接口的所有实现类放入了集合中

[
****.****.withdraw.impl.AlipayPaymentStrategy,
****.****.withdraw.impl.PaymentOnBehalfStrategy,
****.****.withdraw.impl.ThirdPartyPaymentStrategy
]

还测试了 set ,效果和list相同
在这里插入图片描述
测试map, 这里要注意 key 一定要是String类型,打印结果 key为类名,value为策略类实例
在这里插入图片描述

{
alipayPaymentStrategy=xxxxx.withdraw.impl.AlipayPaymentStrategy@3b41e1bf,
paymentOnBehalfStrategy=xxxxx.withdraw.impl.PaymentOnBehalfStrategy@619c93ca,
thirdPartyPaymentStrategy=xxxxx.withdraw.impl.ThirdPartyPaymentStrategy@486e9d1d
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鲸渔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值