Dependency Injection : 의존성 주입
자 단어부터가 벌써 무서워요????? ㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎ……
이걸 이해하기 위해선 차근차근 하나씩 계단을 올라가는 느낌으로 정리를 해보겠습니다!
일단 단어가 2개에요!! 의존성, 주입 그렇죠??
제일 먼저 의존성이라는 단어 먼저 풀이해볼게요!
의존성 : Dependency
자 쉽게 “학생”은 “선생님”에게 의존한다.
틀리지 않은 말이죠? 조금 추상적인 표현이긴 하지만, 간단하게
“학생”이라는 객체는 “선생님”이라는 객체가 있어야지 공부를 할 수 있고, 가르침을 받아서 시험도 보고, 대학교도 가죠???
자 이해가 아마 처음부터 바로 안갈거에요!
그렇다면 코드를 보면서 얘기를 해보겠습니다!
class Student {
private Teacher teacher;
public Student() {
teacher = new Teacher();
}
}
“학생” 이라는 클래스는 현재 “선생님”의 객체를 생성자를 통해서 받아 오고 있습니다!
“선생님” 객체와 “학생” 객체는 지금 연결되 있는 상태이죠??? ⇒ 의존하고있죠??
만약에 “선생님” 객체가 다른 학교로 가게 되어서 새로운 “선생님” 객체가 오면
“학생” 객체는 기존에 수업을 듣고, 공부하던 방식이 달라질 수도 있겠죠???
자! 이게 중요 포인트입니다.
“학생”객체는 “선생님” 객체에 의존하고 있음으로,
“선생님” 객체가 달라짐에 따라 “학생” 객체는 그 영향을 받습니다!
자 그렇다면 실제로 위와 같이 “의존성”을 띄우는 코드를 짠다면, 과연 저게 좋은 방법일까요?
아니죠….!
“선생님”이 달라짐에 따라서 “학생”도 무조건 같이 변해야 하는 상황이 오는건 전혀 좋은 상황이 아닌거죠.
의존성을 띄긴 하지만 실제로는 매우 결합력이 높은 의존성입니다. 그렇다면 어떻게 해결을 해야 할까요?
인터페이스 !
그렇죠. 인터페이스가 중간 역할을 하여서 “선생님”이 달라지더라도, 학생은 다양한 선생님들을 고를 수 있게되는거죠.
즉 더 다양한 의존 관계를 맺을 수가 있다는겁니다 ⇒ 관계가 느슨해지고, 결합도가 낮아진다.
class Student {
private Teacher teacher;
public Student() {
teacher = new Teacher();
}
}
interface manyTeacher{
Teacher1();
Teacher2();
Teacher3();
....
}
class Teacher implements manyTeachers{
public Teacher teacher1(){
return new teacher1;
}
public Teacher Teacher2(){
return new teacher2;
}
public Teacher Teacher3(){
return new teacher3;
}
.....
}
전에 있던 코드와 같이 의존성을 띄우긴 하지만, 달라진건 더 다양한 “선생님들” 에 의존할 수 있는 “학생” 이 되는겁니다.
여기까지 잘 이해가 됬다면 이제는 드디어 오리지널
Dependency Injection : 의존성 주입
자 지금까지는 “학생”이 어떤 “선생님”을 고를지 직접 정하고 있습니다!
“주입” 이라는건 누군가1 에 의해서 무언가를 누군가2 한테 넣는것입니다.
즉 의존성 주입이란 : 의존성을 띄우는 관계이면서, “학생”이 직접 “선생님”을 고르는게 아닌 제 3자가 “선생님”을 결정하고 “학생” 에게 주입해주는겁니다.
자 그러면 이제 이론적으로는 어느정도 이해를 다 한것입니다!
그러면 코드를 직접 한번 만들어봐야겠죠?
여기서 크게 2가지 방법으로 갈립니다
1. 생성자 생성
class Student {
private Teacher teacher;
public Student(Teacher teacher) {
this.teacher = teacher;
}
}
class Principal {
private Student student = new Student(new Teacher());
public void changeTeacher() {
student = new student(new prettyTeacher());
}
}
2. Setter 사용
class Student {
private Teacher teacher;
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}
class Principal {
private Student student = new Student();
public void changeTeacher() {
student.setTeacher(new prettyTeacher());
}
}
아니 그래서 장점은?…
- 의존성이 감소합니다하지만 위와 같이 의존성 “주입”을 하게 되면 결합력이 약해지고, 주입 받는 대상이 변하더라도 구현 자체를 수정할 일이 없을수도,
- 혹은 많이 줄어들게 될겁니다.
- 앞서 말했듯이 그저 의존성만 존재하면, 결합력은 여전히 강합니다.
- 재사용성이 용이해집니다 ⇒ AOC
- 가독성이 높아집니다.
정리하자면?
DI(의존관계 주입)는 객체가 의존하는 또 다른 객체를 외부에서 선언하고 이를 주입받아 사용하는 것이다.
끗-
생각보다 어려운 내용이였습니다. 근데 재밌었습니다 ! from. 변태
'Spring & Spring Boot' 카테고리의 다른 글
Spring bean(빈이란?) (0) | 2023.01.16 |
---|---|
IOC (Inversion Of Control) 제어의 역전 .feat “Container” (0) | 2023.01.16 |
Spring Framework 파일업로드 하기 (2) | 2023.01.16 |
Spring Interceptor 핸들러 가로채기 🙂 (4) | 2023.01.16 |
MVC 패턴?…What the….?? (0) | 2023.01.16 |