10/9 [Spring] DI(의존성 주입)
Spring 강의를 듣고 정리한 내용입니다.
DI(의존성 주입)
의존성 주입은 듣고 있는 강의 강사님이 말씀하시길 부품 조립이라고 이해하면 된다고 하셨다.
의존성 주입의 방식에는 크게 두가지가 있다.
Composition has a
-
생성자 방식
생성자 방식은 A 객체의 기본 생성자를 호출하면 B도 자동으로 호출되는 것처럼 의존성이 높은 방법이다.
class A {
private B b;
public A() {
b = new B();
}
}
Association has a
-
setter 방식
setter 방식은 외부에서 만들어진 객체 b를 A 객체에 주입(injection)하는 방식으로 생성자 방식에 비해 의존성이 낮다.
class A {
private B b;
public A() {}
public void setB(B b) {
this.b = b;
}
}
예시
다음은 자바 코드를 .xml 외부 파일을 이용해 소스코드 변경 없이 외부 설정을 하는 예시이다.
public class Program {
public static void main(String[] args) {
Exam exam = new NewlecExam();
ExamConsole console = new InlineExamConsole();
console.setExam(exam);
}
}
해당 코드의 인터페이스와 클래스에 대한 간략한 설명은 다음과 같다.
- Exam : 점수의 합과 평균을 구하는 total(), avg() 정의한 Interface
- ExamConsole : 점수를 출력하는 print() 정의한 Interface
- InlineExamConsole : print() 내용 작성, ExamConsole Implement 받은 자식 클래스
이 자바코드를 xml파일로 바꾸면 다음과 같다.
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Exam exam = new NewlecExam();-->
<bean id="exam" class="spring.di.entity.NewlecExam"/>
<!-- ExamConsole console = new GridExamConsole();-->
<bean id="console" class="spring.di.ui.GridExamConsole">
<!-- console.setExam(exam);-->
<property name="exam" ref="exam"/>
</bean>
</beans>
-
<bean id=”exam” class=”spring.di.entity.NewlecExam”/>
id 속성에는 Spring 컨테이너에서 객체를 식별하기 위한 고유의 이름을 사용하되 중복되지 않는 어떤 이름 사용할 수 있다. class에는 패키지 경로를 포함한 클래스 이름을 입력해준다.
-
<bean id=”console” class=”spring.di.ui.GridExamConsole”><bean/>
첫번쨰와 동일하다.
-
<property name=”exam” ref=”exam”/>
name 속성은 setter 메서드와 매핑되는 필드이름이다. 이 코드의 경우 GridExamConsole클래스의 console이라는 객체의 exam이라는 필드에 값을 set하는 것이다. ref 속성은 다른 bean을 참조하는 역할을 한다.
ApplicationContext
: 스프링에서 DI, 지시서를 읽고 생성, 조립하는 spring의 객체(인터페이스 명)
ApplicationContext context = new ClassPathXmlApplicationContext("config.xml"); // 루트에 config.xml 파일을 두었다는 의미
-
종류
아래 객체들은 지시서(config.xml)를 전달하는 방식으로 나뉜다.
-
ClassPathXmlApplicationContext
App의 루트로부터 경로를 지정
-
FileSystemXmlApplicationContext
파일 시스템의 경로를 이용해서 지정
-
XmlWebApplicationContext
웹의 URL을 통해 지정
-
AnnotationConfigApplicationContext
파일이 아닌 Annotation으로 지정
-
댓글남기기