Makudex
Makudex

Reputation: 1082

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?

Upvotes: 12

Views: 8551

Answers (3)

Anandkumar
Anandkumar

Reputation: 1512

Import - is static import,

Dependency Injection - dynamic import

In addition to @Nirav Patel answer, I would like to add a scenario. If we want to have a different implementation in different environment (Dev/QA/UAT/Prod), you don't need to change the code, you can achieve it using DI and also changing the configuration in that environment.

Watch this video, if you need a detailed explanation

https://www.udemy.com/spring-framework-video-tutorial/learn/v4/t/lecture/4635190

(By the way, it's a free course in Udemy)

Instructor sends a mock email in dev and real email using smtp, just by changing the configuration.

Upvotes: 3

Nirav Patel
Nirav Patel

Reputation: 1304

Dependency Injection is used to remove need for the code changes and make it possible using configuration only.

I.e., you have

Interface B {
//some methods
}
class X implements B{

// implement some methods of B

}

class Y implements B{

// implement some methods of B

}
// code without using Dependency Injection
 class A1{
private B objB = New X();
//remaining code
}

class A2{
private B objB = New X();
//remaining code
}

Note: if you need to change for some reason objB instance with class Y, you need to make code changes in both classes A1 and A2.

// code using Dependency Injection
 class A1{

@Autowired
private B objB;
//remaining code
}

class A2{
@Autowired
private B objB;
//remaining code
}

Here you just need to change configuration of creating instances for interface B and change required class from X to Y that's it. No changes in any of java classes (here A1 and A2).

Upvotes: 6

Elliott Frisch
Elliott Frisch

Reputation: 201527

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

Upvotes: 8

Related Questions