Could someone please explain to me why do we need to use the spring's dependency injection when you can just import a java class like:
import com.package.somejavaclass
I just wonder why?
Dependency injection enables you to turn regular Java classes into managed objects and to inject them into any other managed object. Using dependency injection, your code can declare dependencies on any managed object.
Probably the main benefit of dependency injection is maintainability. If your classes are loosely coupled and follow the single responsibility principle — the natural result of using DI — then your code will be easier to maintain. Simple, stand-alone classes are easier to fix than complicated, tightly coupled classes.
More specifically, dependency injection is effective in these situations: You need to inject configuration data into one or more components. You need to inject the same dependency into multiple components. You need to inject different implementations of the same dependency.
A basic benefit of dependency injection is decreased coupling between classes and their dependencies. By removing a client's knowledge of how its dependencies are implemented, programs become more reusable, testable and maintainable.
Dependency Injection (and Inversion of Control) have nothing to do with import
. Dependency injection allows you to make runtime decisions instead of compile-time decisions. For example, how your class gets a database Connection
. That is configuration over hard-coding.
import
The import
statement allows you to not specify the fully-qualifed name of a class. That is, without import java.util.Date;
you can still (for example)
System.out.println(new java.util.Date());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With