我見過例如由Martin Fowler Here重構有條件的多態性彈簧引導代碼
不知道我怎麼能在春天啓動的方式實現它(IOC)在重構給出。
我正在處理spring web應用程序。 我有一個REST控制器,它接受studentId
和fileType
和導出數據學生給定fileType
格式。 控制器調用ExportService
exportFile()
方法,它看起來像
@Service
public class ExportServiceImpl implements ExportService {
public void exportFile(Integer studentId, String fileType) {
if (XML.equals(fileType)) { exportXML(studentId);}
else if()... // and so on for CSV, JSON etc
}
}
重構條件多態,
首先,我創建抽象類,
abstract class ExportFile {
abstract public void doExport(Integer studentId);
}
然後我,每種文件類型導出創建服務。對於下面的示例XML導出是一種服務,
@Service
public class ExportXMLFileService extends ExportFile {
public void doExport(Integer studentId) {
// exportLogic will create xml
}
}
現在我ExportService應該是什麼樣子,
@Service
public class ExportServiceImpl implements ExportService {
@Autowired
private ExportFile exportFile;
public void exportFile(Integer studentId, String fileType) {
exportFile.doExport(studentId);
}
}
現在我在這裏停留:(
無法獲取, 如何@Autowired
ExportFile
將根據fileType
知道具體哪項服務?
請做正確我如果我錯了。您的迴應將不勝感激:)