Spring boot 之 動態的獲取不同的實現類

  1. 聲明接口

// ApiResult 就是返回值,可以根據自己的需求,定義
/**

  • 根據不同的處理類型,來選擇不同的處理方案
  • @author erjun
  • */
    public interface StorageType {
    ApiResult handleStorage();
    }

  1. 定義兩個實現類

@Service("hdfsStorageType")
public class HdfsStorageType implements StorageType {

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

}

@Service("ftpStorageType")
public class FtpStorageType implements StorageType {

@Override
public 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的上下文
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
}

// 註冊接口StorageType的所有實現的bean,
// 可以按照自己的規則放入 註冊中心 serviceImpMap裏
@Override
public void afterPropertiesSet() throws Exception {
    Map<String, StorageType> 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 之 動態的獲取不同的實現類

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章