Spring学习总结(8)-接口多个实现类的动态调用
需求描述:当一个接口有2个以上的实现类时,调用方需要根据参数选择只其中一个实现类
Spring版本:5.1.8.RELEASE
1. 接口和实现类
/**
* 接口
*/
public interface OrderInfoDao {
void queryOrderList();
}
/**
* 实现类A
*/
@Component
public class OrderInfoDaoAImpl implements OrderInfoDao {
@Override
public void queryOrderList() {
System.out.println("Dao A queryOrderList");
}
}
/**
* 实现类B
*/
@Component
public class OrderInfoDaoBImpl implements OrderInfoDao {
@Override
public void queryOrderList() {
System.out.println("Dao B queryOrderList");
}
}
现在要求Service层要根据参数输入A或B动态选择实现类。
2. 使用ApplicationContextAware接口实现
@Component
public class OrderInfoServiceImpl implements ApplicationContextAware {
private ApplicationContext applicationContext;
public void query(String username){
OrderInfoDao dao = null;
if("A".equals(username)){
dao = (OrderInfoDao) applicationContext.getBean("orderInfoDaoAImpl");
}
else if("B".equals(username)){
dao = (OrderInfoDao) applicationContext.getBean("orderInfoDaoBImpl");
}
dao.queryOrderList();
}
/**
* ApplicationContextAware接口的实现类,可以拿到上下文
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
3. 使用@Autowired注入Map实现
@Component public class OrderInfoServiceImpl { /** * 用这个方式Spring会在初始化时,自动把OrderInfoDao接口的实现类,全放到Map里 */ @Autowired private Map<String, OrderInfoDao> map; public void query(String username){ // 拼接Dao实现类的名称 String daoName = "orderInfoDao" + username + "Impl"; OrderInfoDao dao = map.get(daoName); if(dao != null){ dao.queryOrderList(); } } }
4. 测试
public class OrderInfo1Test { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); OrderInfoServiceImpl service = context.getBean(OrderInfoServiceImpl.class); service.query("B"); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通