What are the benefits of dependency injection containers?

前端 未结 16 2757
南笙
南笙 2020-12-02 04:09

I understand benefits of dependency injection itself. Let\'s take Spring for instance. I also understand benefits of other Spring featureslike AOP, helpers of different kind

16条回答
  •  暖寄归人
    2020-12-02 05:05

    I have your answer

    There are obviously trade offs in each approach, but externalized XML configuration files are useful for enterprise development in which build systems are used to compile the code and not your IDE. Using the build system, you may want to inject certain values into your code - for example the version of the build (which could be painful to have to update manually each time you compile). The pain is greater when your build system pulls code off of some version control system. Modifying simple values at compile time would require you to change a file, commit it, compile, and then revert each time for each change. These aren't changes that you want to commit into your version control.

    Other useful use cases regarding the build system and external configs:

    • injecting styles/stylesheets for a single code base for different builds
    • injecting different sets of dynamic content (or references to them) for your single code base
    • injecting localization context for different builds/clients
    • changing a webservice URI to a backup server (when the main one goes down)

    Update: All the above examples were on things that didn't necessarily require dependencies on classes. But you can easily build up cases where both a complex object and automation is necessary - for example:

    • Imagine you had a system in which it monitored the traffic of your website. Depending on the # of concurrent users, it turns on/off a logging mechanism. Perhaps while the mechanism is off, a stub object is put in its place.
    • Imagine you had a web conferencing system in which depending on the # of users, you want to switch out the ability to do P2P depending on # of participants

提交回复
热议问题