Dependency injection

Han sang yeob·2021년 4월 27일
1

Java Spring

목록 보기
2/2

One of the design pattern in dependceny injection. It does not metter what language we use, we need this concept.

1. What is dependency injection?

We build object in software(espcially in object - oriented program) this is why need to understand that some object depend on one object.
In real - life example, let's say that we are making Apple labtop. In labtop, there are certain parts that is complasary like screen,
RAM, hard drive etc.. But Apple don't build every part for their own. There are so many compaines that support Apple to build labtop.
In code,

class Laptop
{
	HardDrive obj;
    Ram obj2;
    Screen obj3;
}

Now let's say that they use Hitachi harddrive,

class Laptop
{
	HitachiHD obj1 = new HitachiHD();
}

But, what if in the future, we want to change it to different hard drive? We need to achive the concept of 'loose coupling', right?
This is why we use 'abstruct'.

HardDrive <- HitachiHD

so when we extenciate it, it would be something like,

class Laptop
{
	HardDrive obj1 = new HitachiHD();
}

in this way, we can change it to another brand more easy. But there is one question here. We are 'hard coding it'. This is a bad thing. when we say "new", it becomes 'tight coupling'. So we can make someone else to give this dependency. The Laptop object is dependent on harddrive object. So we will 'inject' the dependency inside laptop class.
We have concept of 'dependency injection container' or Spring Conatiner in Java. So they are responsible to create an object and
then injecting in our class. All this is when we have to do configuration. In jave we have Spring frame work to do this for us.
First we create xml file and in the xml file, we can mention
"Hey, someone is asking for hard drive. Give this object".
when we mention about xml, we can edit it in the future so that is not tight coupled

@Component 
class HitachiHD inplement HardDrive
{
	...
	...
}

@Component make them component of Spring framework.

How about this?

class Laptop
{
	HardDrive obj1 = new HitachiHD();
}

we can change it into like,

class Laptop
{
	 @Autowired
	HardDrive obj1;
}

2.Why we need this??

Is the answer is because of tight coupling? Yes! We dont want to achive tight coupling. Plus testing. When the Apple test their labtop, they need to test the hard drive speratatly.

profile
Learning IT in Vietnam

0개의 댓글