在 spring-boot 代码中重构条件多态性

Refactor conditional to polymorphism in spring-boot code

我看过 Martin Fowler 在 Refactoring 中给出的示例 Here

不确定如何在 spring-引导方式 (IoC) 中实现它。

我正在开发 spring 网络应用程序。 我有一个 REST 控制器,它接受 studentIdfileType 并以给定的 fileType 格式导出 Students 的数据。 控制器调用 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
    }
}

重构条件多态性,

首先我创建了摘要class,

abstract class ExportFile {
    abstract public void doExport(Integer studentId);
}

然后我为每个文件类型导出创建服务。例如XML export 下面是一个服务,

@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 知道要引用哪个具体服务?

如有错误请指正。非常感谢您的回复:)

您将需要实施工厂模式。我做了类似的事情。你会有一个ExportServiceFactory,它会根据具体的输入参数return具体实现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
    }

}

如您所见,我使用了 Springs @Qualifier,它将确定要注入的实现。

然后在您的代码中,每当您需要使用 ExportService 时,您将注入工厂并获取正确的实现,例如

  ...
  @Autowired
  private ExportServiceFactory exportServiceFactory;

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

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