一个接口有多个实现类,怎么让springboot自动决定执行哪个实现类的代码

@Component
public class ImplementSubformFactory implements ApplicationContextAware {

    private static Map<String, ImplementSubformService> productMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	//获取ImplementSubformService的所有实现类
        Map<String, ImplementSubformService> map = applicationContext.getBeansOfType(ImplementSubformService.class);
        for (Map.Entry<String, ImplementSubformService> data : map.entrySet()) {
	//在实现类上看有没有使用注解@ImplementSubform
            ImplementSubformService subform = data.getValue();
            Class<? extends ImplementSubformService> aClass = subform.getClass();
            ImplementSubform annotation = AnnotationUtils.findAnnotation(aClass, ImplementSubform.class);
            if (null != annotation) {
		//有使用,则将注解的type值作为key,实现类作为value存到全局的map中
                productMap.put(annotation.type(), subform);
            }
        }
    }
	//在业务中,直接根据type值就可以拿到具体实现类,然后就执行具体的代码了
    public static ImplementSubformService makeProduct(String name) {
        return productMap.get(name);
    }
}
posted @ 2023-02-22 11:26  晚风没有颜色  阅读(321)  评论(0编辑  收藏  举报