简体   繁体   English

Java中的依赖注入-正确用法

[英]Dependency Injection in java - Correct usage

As a new user to programming in general, I'm trying to understand dependency injection. 作为一般编程的新用户,我试图理解依赖注入。

Is there ever a time where it's appropriate to instantiate an object within another class or is the idea that all objects will be instantiated in Main? 有没有什么时候可以在另一个类中实例化一个对象,还是所有对象都将在Main中实例化的想法?

Yes, there are plenty of times where it's appropriate to instantiate objects inside other objects. 是的,很多时候都适合在其他对象中实例化对象。 Dependency injection is for dependencies, not for data objects and such. 依赖性注入是针对依赖性的,而不是针对数据对象等的。

But even in the case of "dependencies", there are cases where it's fine to create them inside another object. 但是即使在“依赖关系”的情况下,也可以在另一个对象中创建它们。 If the objects you're creating are logically part of the object creating them, then dependency injection may be overkill. 如果要创建的对象在逻辑上是创建它们的对象的一部分,则依赖项注入可能会过大。 Sometimes I'll organize code into multiple classes without intending the smaller pieces to be standalone in any way. 有时,我会将代码组织成多个类,而不希望较小的部分以任何方式独立。 In those cases I may just new them inside something else. 在这种情况下,我可能只是new他们里面别的东西。

But it's a judgment call. 但这是一个判断电话。 Even in such cases it may be nice to be able to unit test the smaller bits in isolation, for example. 例如,即使在这种情况下,也可以对较小的位进行隔离的单元测试可能会很好。

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

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