2016-04-11 35 views
0

我見過例如由Martin Fowler Here重構有條件的多態性彈簧引導代碼

不知道我怎麼能在春天啓動的方式實現它(IOC)在重構給出。

我正在處理spring web應用程序。 我有一個REST控制器,它接受studentIdfileType和導出數據學生給定fileType格式。 控制器調用ExportServiceexportFile()方法,它看起來像

@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); 
    } 
} 

現在我在這裏停留:(

無法獲取, 如何@AutowiredExportFile將根據fileType知道具體哪項服務?

請做正確我如果我錯了。您的迴應將不勝感激:)

回答

1

您將需要實施工廠模式。我做了類似的事情。您將有一個ExportServiceFactory這將根據具體的輸入參數返回的具體實施ExportService,這樣的事情:

@Component 
class ExportServiceFactory { 

    @Autowired @Qualifier("exportXmlService") 
    private ExportService exportXmlService; 

    @Autowired @Qualifier("exportCsvService") 
    private ExportService exportCsvService; 

    public ExportService getByType(String fileType) { 
     // Implement method logic here, for example with switch that will return the correct ExportService 
    } 

} 

正如你可以看到我用溫泉@Qualifier這將確定哪些執行將被注入。

然後在您的代碼中,每當您需要使用ExportService時,您將注入工廠並獲取正確的實現,例如,

... 
    @Autowired 
    private ExportServiceFactory exportServiceFactory; 

    ... 
    // in method, do something like this 
    exportServiceFactory.getByType(fileType).doExport(); 

我希望這能幫助你走上正確的軌道。至於工廠方法中的開關 - 沒問題,因爲現在你已經分離了邏輯以從與它沒有任何關係的代碼中檢索特定的實現。