使用InitializingBean接口
springboot中在启动的会自动把所有的实现同一个接口的类,都会转配到标注@Autowired的list里面
而且实现了InitializingBean接口,在启动的赋值的时候,我们会把所有的策略类,重放到map中,我们在使用的时候,更具唯一code,找到对应的实现类即可。
public class xxxxx implements InitializingBean {@Autowiredprivate List<策略类的接口> xxxxLists;private Map<每一个策略的唯一code,策略类的接口> xxxxMap;@Overridepublic void afterPropertiesSet() throws Exception {xxxxMap = xxxxLists.stream().collect(Collectors.toMap(策略类唯一code,Function.identity()));}
}
实现ApplicationContextAware类
通过后置处理器,把容器相同的类找到,然后加载到map中使用
public class xxxxxx implements ApplicationContextAware {private Map<每一个策略的唯一code,策略类的接口> xxxxMap;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {Map<String, CityInfoServiceController> beansOfType = applicationContext.getBeansOfType(xxxxxx.class);beansOfType.forEach((key,value)->{xxxxMap.put(value.getCode(),value);});}
}
每一个策略接口
public interface MyHandle {//每一个策略都有一个唯一一个code(建议使用枚举列出,方便使用)public String getHandleCode();//实现具体策略实现(可以返回具体数据,也可以返回void)public void handleMethod(Object data);}