A
A
Alina Mitrokhina2019-10-10 17:34:52
Java
Alina Mitrokhina, 2019-10-10 17:34:52

What is the difference between DI through constructor, field and method?

1. In my understanding of DI through the constructor is that we pass dependencies to the class that are critical for its operation and without them it simply cannot work. For example, the Car class has an Engine. We pass it to the constructor. If we don't pass in an Engine implementation, then the class simply won't work.
2. DI through the field is a "low priority" dependency injection, i.e. for example Retrofit can work without a logger. But if we want, we can specify a logger for the http client.
3. DI via a method is when we pass a dependency to a particular method that is only used in that method.
Can you please add or criticize what I wrote?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-10-10
@fursa08

It's not about criticality and priorities, it's about the pros and cons of each approach in specific situations. Constructor injection is convenient, allows you to initialize the final fields and guarantees the correct state of the object, but because of it, the list of constructor arguments can swell. Implementation in the field has a lot of disadvantages, but it can be used with code generation. Implementation through the method is an average option, moderately combining advantages and disadvantages.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question