关键在于: applicationContext.getBeansOfType(ChartService.class);
获得Map对象的key为实现类的名称如:chartSimpleServiceImpl
获得Map对象的value为实现类对象如: com.read.data.cms.service.impl.ChartExtraServiceImpl@5c85b6e9
applicationContext的获取方法有很多种,我这里暂列两种
第一种方式实现接口所有类集合(注解)
@Autowire
private ApplicationContext applicationContext;
Map<String,ChartService> res = applicationContext.getBeansOfType(ChartService.class);
res.get("实现类的字符串如:chartSimpleServiceImpl")
res.get获得的结果,就是当前实现类对象
第二种方式实现接口所有类集合(实现接口)
/**
* @author: tianyong
* @Time: 2019/6/26 11:17
* @description:服务工厂(主要用于动态注入接口实现类)
*/
@Component
public class ServiceFactory implements ApplicationContextAware {
//定义成员变量
private static Map<String,ChartService> res;
/**
* @author: tianyong
* @time: 2019/6/27 16:04
* @description:设置上下文参数
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
res = applicationContext.getBeansOfType(ChartService.class);
}
/**
* @author: tianyong
* @time: 2019/6/27 16:05
* @description:根据标记返回当前接口实现类
*/
public static <T extends ChartService> T getServices(String flag){
return (T)res.get(flag);
}
}
如果对您有帮助,麻烦关注本人公众号:周三想吧