简体   繁体   中英

Spring Dependency Injection vs. Writing to Interfaces

I have a few questions about Spring paradigm in Java:

1) Suppose I have an application where I write everything to interfaces, and then at the very last moment, somewhere in my actual main() or maybe in a config file, I define my specific classes to be used. Have I achieved the same objective as Spring? In that case, why do I need Spring's DI? Writing to interfaces, and leaving specifics till the very last moment, is standard practice that programmers have been using for decades.

2) If the objection is to new'ing objects at some (final) point in time, this has to be done at some point in my interface-driven app, but what's wrong with that? How does having a "new" statement make a class unusable or untestable - or is it just readability/transparency?

3) People say that declaratively using objects "gets rid of dependencies." But we still have a dependency: we have to import a new class, even if we don't "new" it, before we can compile the code?

Some people, like me, prefer to configure the wiring of dependencies and interface implementations using Spring XML rather than hardcode them. All the wirings are in one place (assuming you are not using annotations) and I can also argue that modifying the configuration of the XML file is easier than modifying code. You can also tweak the Spring file between runs of your application if there is something that needs to change.
Spring is a good framework that has been around for a while. I find it's really really good at Dependency Injection (DI). While there is nothing "wrong" with your approach in #1, I think using Spring will give you a more robust implementation. Why reinvent the wheel?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM