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

时间:2015-03-10 19:06:07

标签: java spring factory-pattern strategy-pattern

我正在创建一个策略工厂,它通过applicationContext加载所有具有特定注释的bean。在我的服务中,我想将一个字符串参数传递给这个工厂,它应该返回正确的实现。但我面临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);

这是我的策略课程:

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

1 个答案:

答案 0 :(得分:1)

您将bean Class放在Map中,而不是bean本身。

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

应该是

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