spring - 以 spring-boot 代码中的多态性为条件进行重构

标签 spring polymorphism refactoring conditional-statements code-cleanup

我看过 Martin Fowler 在《重构》中给出的示例 Here

不确定如何以 spring-boot 方式(IoC)实现它。

我正在开发 Spring Web 应用程序。 我有一个 REST Controller ,它接受 studentIdfileType并导出给定 fileType学生的数据格式。 Controller 来电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 就会知 Prop 体要引用哪个服务?

如果我错了,请纠正我。我们将非常感谢您的回复:)

最佳答案

您将需要实现工厂模式。我做了类似的事情。您将拥有一个 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
    }

}

如你所见,我使用了 Springs @Qualifier这将决定将注入(inject)什么实现。

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

  ...
  @Autowired
  private ExportServiceFactory exportServiceFactory;

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

我希望这能帮助您走上正确的道路。至于工厂方法中的切换 - 没关系,因为您现在已经解耦逻辑以从与之无关的代码中检索特定的实现。

关于spring - 以 spring-boot 代码中的多态性为条件进行重构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36542564/

相关文章:

java - ClassNotFoundException : org. hibernate.service.jndi.JndiException

java - 我应该为负责在文件系统上持久保存数据的 bean 使用 @Repository Spring 注释吗?

django - Django 模型中的多态性

python - 如何在 Python 中清理这个选择排序函数?

spring - Mockito 注入(inject)不适用于构造函数和 setter 模拟

java - Spring 启动 Controller 404

c++ - 在这种情况下,我应该/如何避免垂头丧气?

c++ - 具有不同节点类型的二叉树

组合目录和文件路径 - C

ruby-on-rails - ruby - 重构 if else 语句