Makudex Makudex - 8 months ago 44
Java Question

Why use Dependency injection when you can import a java class?

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?


DI and IoC

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.


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());