博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring boot 之 动态的获取不同的实现类
阅读量:6855 次
发布时间:2019-06-26

本文共 1591 字,大约阅读时间需要 5 分钟。

  1. 声明接口

// ApiResult 就是返回值,可以根据自己的需求,定义

/**

  • 根据不同的处理类型,来选择不同的处理方案
  • @author erjun
  • */

    public interface StorageType {
    ApiResult handleStorage();
    }

  1. 定义两个实现类

@Service("hdfsStorageType")

public class HdfsStorageType implements StorageType {

@Overridepublic ApiResult handleStorage() {    System.out.println("-----hdfs---storageType-----");    return null;}

}

@Service("ftpStorageType")

public class FtpStorageType implements StorageType {

@Overridepublic ApiResult handleStorage() {    System.out.println("-----ftp---storageType-----");    return null;}

}

  1. 定义一个Register类

将多个子类,注册到一个map容器里

@Service("register")

public class Register implements InitializingBean, ApplicationContextAware {
private Map<String, StorageType> serviceImpMap = new HashMap<String, StorageType>();

private ApplicationContext applicationContext;// 获取Spring的上下文@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {    this.applicationContext = applicationContext;}// 注册接口StorageType的所有实现的bean,// 可以按照自己的规则放入 注册中心 serviceImpMap里@Overridepublic void afterPropertiesSet() throws Exception {    Map
beanMap = applicationContext.getBeansOfType(StorageType.class); String name = null; for (StorageType storageType : beanMap.values()) { name = storageType.getClass().getSimpleName(); System.out.println("---key:\t" + name); // 将类名,作为 key, serviceImpMap.put(name, storageType); }}public StorageType getStorageType(String name) { return serviceImpMap.get(name);}

}

  1. controller层进行调用

Spring  boot 之 动态的获取不同的实现类

  1. POST 测试:

Spring  boot 之 动态的获取不同的实现类

Spring  boot 之 动态的获取不同的实现类

结果:

Spring  boot 之 动态的获取不同的实现类

转载于:https://blog.51cto.com/xingej/2045657

你可能感兴趣的文章
分布式系统理论基础 - CAP
查看>>
跨站脚本功攻击,xss,一个简单的例子让你知道什么是xss攻击
查看>>
win 停止tomcat
查看>>
Laravel-mix 中文文档
查看>>
Eureka核心知识点
查看>>
Sword STL迭代器prev,next相关函数
查看>>
小学生坐马桶上都看得懂的加密与通讯
查看>>
MS CRM 2011 如何从外部连接CRM 二
查看>>
Eclipse构建路径
查看>>
10条不可不知的手机礼仪 看看你犯过哪几项?
查看>>
:c#的remoting里,CallContext.GetData获得的对象老是空的?该怎么处理
查看>>
.NET设计模式(2): 工厂方法模式
查看>>
appium 自动化测试之知乎Android客户端
查看>>
如何使用Log4j?
查看>>
发送一个记录数据包
查看>>
开发资源汇聚 - jQuery (持续更新中)
查看>>
界面演示
查看>>
使用SQL Database Migration Wizard把SQL Server 2008迁移到Windows Azure SQL Database
查看>>
给线程发送消息让它执行不同的处理
查看>>
Bitcoin Cash到底是一种协议、还是一种产品?
查看>>