2016-04-11 36 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(); 

我希望这能帮助你走上正确的轨道。至于工厂方法中的开关 - 没问题,因为现在你已经分离了逻辑以从与它没有任何关系的代码中检索特定的实现。