- 聲明接口
// ApiResult 就是返回值,可以根據自己的需求,定義
/**
- 根據不同的處理類型,來選擇不同的處理方案
- @author erjun
-
*/
public interface StorageType {
ApiResult handleStorage();
}
- 定義兩個實現類
@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;
}
}
- 定義一個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);
}
}
- controller層進行調用
- POST 測試:
結果: