In a project using a DI framework, should NEVER use the “new” operator?

I'm trying to bow my head to dependency injection.

One of the things that I am confused about is whether I need to control all the object-objects using the DI framework (Spring, Guice, etc.).

Or, if not, how do you determine which objects are created by the wireframe and which objects are created using the new operator?

+7
java spring new-operator dependency-injection guice
source share
5 answers

No, there is still room for a new one. Not all objects must be managed by a DI factory.

You can easily define the classes that should be under the DI factory control, since they usually include interfaces and implementations.

Any local object in the implementation has the right to call new. Model objects created to meet a specific use case must be created by calling new ones and passing parameter values ​​for that particular instance.

+11
source share

I found this post from Miško Hevery very useful in distinguishing which objects should be introduced as dependencies and which they should create. He distinguishes between the classes New and Injectable.

+10
source share

I would say that simpler objects without "real" dependencies should not be introduced. It can be data objects or, of course, exceptions, etc.

"eliminating the new operator" basically just gives a good guide where to look for DI-capable things.

+2
source share

As long as novelty doesn't stop you from isolating behaviors for testing, you're fine. Examples may be collections or value types used in an implementation, but not actually performing “work with objects” as such.

The focus on the word “addiction” is the object in question, is it somehow supposed that the contained object fulfills its true purpose for the existing one? If so, it should be administered externally.

+1
source share

new does not necessarily exclude the DI framework. For example, in Spring, you can use magic when loading classes to inject dependencies for any object created with new .

Thus, although new and container-managed DIs in java are usually mutually exclusive, it is not tough and fast.

+1
source share

All Articles