被spring管理的类不能被new出来,否则@Autowired注入为null
@Component
public class OrderContext {
public static Map<String, OrderStrategy> orderStrategyMap;
@Autowired
private void setOrderStrategyMap(List<OrderStrategy> orderStrategies) {
// 注入各种类型的订单处理类
orderStrategyMap = orderStrategies.stream().collect(
Collectors.toMap(orderStrategy -> AnnotationUtils.findAnnotation(orderStrategy.getClass(), OrderSource.class).source(),
v -> v, (v1, v2) -> v1));
}
// 获取具体策略类
public static OrderStrategy getStrategy(String orderSource) {
if (null == orderStrategyMap) {
return null;
}
return orderStrategyMap.get(orderSource);
}
}