简体   繁体   English

Spring依赖注入与编写接口

[英]Spring Dependency Injection vs. Writing to Interfaces

I have a few questions about Spring paradigm in Java: 我对Java中的Spring范式有一些疑问:

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. 1)假设我有一个应用程序,在其中我将所有内容都写到接口,然后在最后一刻,在我实际的main()或配置文件中的某个地方,我定义了要使用的特定类。 Have I achieved the same objective as Spring? 我实现了与Spring相同的目标吗? In that case, why do I need Spring's DI? 在那种情况下,为什么我需要Spring的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? 2)如果异议是在某个(最终)时间点对新对象进行的,则必须在我的界面驱动的应用程序中的某个时候进行,但是这有什么问题呢? 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." 3)人们说,声明式地使用对象“摆脱了依赖”。 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. 和我一样,有些人更喜欢使用Spring XML配置依赖项和接口实现的连接,而不是对其进行硬编码。 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. 所有的连接都在一个地方(假设您没有使用批注),我还可以说修改XML文件的配置比修改代码更容易。 You can also tweak the Spring file between runs of your application if there is something that needs to change. 如果需要更改某些内容,还可以在应用程序的运行之间调整Spring文件。
Spring is a good framework that has been around for a while. Spring是一个很好的框架,已经存在了一段时间。 I find it's really really good at Dependency Injection (DI). 我发现依赖注入(DI)确实非常好。 While there is nothing "wrong" with your approach in #1, I think using Spring will give you a more robust implementation. 尽管在#1中您的方法没有什么“错误”,但我认为使用Spring将为您提供更可靠的实现。 Why reinvent the wheel? 为什么要重新发明轮子?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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