Understanding the need for a DI framework

前端 未结 12 1811
长情又很酷
长情又很酷 2020-12-07 12:39

This might be a naive question. I\'m currently learning the Spring framework and dependency injection. While the basic principle of DI is rather easy to grasp, it\'s

12条回答
  •  星月不相逢
    2020-12-07 13:25

    Granted, this is a contrieved example, and with more complex object relationships it might be more efficient to stash up an XML file than writing it programmatically, but surely there must be more to it than that?

    I think it makes more sense to put the "wiring up" in a configuration file rather than doing it manually in code for several reasons:

    1. The configuration is external to your code.
    2. Changes to the wiring up (to tell your sawmill to use a different instance of Saw) can simply be made to the external (XML) file and do not require changing code, re-compiling, re-deploying, etc.
    3. When you have dozens of classes, and several layers of injection (for example: you have a web Controller class which gets a Service class which contains your business logic, which uses a DAO to obtain Saws from the database, which gets a DataSource injected into it, etc.), manually wiring up the collaborators is tedious and requires a few dozen lines of code that do nothing but wiring up.
    4. This is somewhat less of a clear-cut "benefit", but by having all of the 'wiring up' external to the code, I think it helps reenforce to developers the ideas that are at the core of dependency injection, specifically the idea of coding to the interface, not the implementation. With manual wiring up, it can be easy to slip back into old ways.

提交回复
热议问题