Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 319
Makudex Avatar asked Sep 03 '15 02:09

Makudex


People also ask

Why do we need dependency injection in Java?

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.

Why should I use dependency injection?

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.

When should dependency injection be used?

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.

Which choice is a benefit of using dependency injection in Java?

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.


1 Answers

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.

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());
like image 135
Elliott Frisch Avatar answered Nov 02 '22 22:11

Elliott Frisch