如何将 applicationContext 中加载的 spring 个 bean 转换为接口?

How to cast spring beans loaded in applicationContext to interface?

我正在创建一个策略工厂,它通过 applicationContext 加载所有具有特定注释的 bean。在我的服务中,我想将一个字符串参数传递给这个工厂,它应该 return 我正确的实现。但是我遇到了 Cast Exception:

    @Autowired
private ApplicationContext applicationContext;

private Map<String,Object> strategyCache = new HashMap<>();


@PostConstruct
public void init(){

    Map<String, Object> annotatedBeanClasses = applicationContext.getBeansWithAnnotation(SimulationType.class);

    for(Object bean : annotatedBeanClasses.values()){

        SimulationType strategyAnnotation = AnnotationUtils.findAnnotation(bean.getClass(), SimulationType.class);
        strategyCache.put(strategyAnnotation.platform(),bean.getClass());

    }
}


public SimulationStrategy getSimulationStrategy(String platform){
    SimulationStrategy strategy = (SimulationStrategy) strategyCache.get(platform);
    return strategy;
}

我想这样称呼我的服务:

SimulationStrategy strategy = simulationFactory.getSimulationStrategy(platform);

这是我的策略class:

@Component
@SimulationType(platform="costumer")
public class ProductSimulation extends SimulationTemplate {
    Do Stuff....
}

您将 bean 的 Class 放入 Map,而不是 bean 本身。

strategyCache.put(strategyAnnotation.platform(), bean.getClass());

应该是

strategyCache.put(strategyAnnotation.platform(), bean);