简体   繁体   中英

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?

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.

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.

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