본문 바로가기

Framework

스프링 / DI패턴 / 의존관계

#스프링의 개념

서비스 지향적인 프레임워크로 하나의 완성된 컴포넌트를 여러 서비스 클래스들을 조합하여 작업을 쉽게 하고 의존도가 낮은 코드를 만드는 프레임워크


#스프링의 특징

경량 컨테이너(집합소)
자바 객체를 담고 있는 컨테이너
생성, 소멸과 같은 라이프 사이클 관리
객체를 가져와 사용가능
인터페이스를 사용하여 의존관계 약화
DI(Dependency Injection : 의존관계)지원
AOP(Aspect Oriented Programming : 관점지향)지원
MVC 지원
POJO(Plain Old Java : JDK만 있으면 다른 컨테이너를 필요치 않음)지원


#DI 패턴이란

객체 간의 의존 관계를 객체 자신이 아닌 외부의 조립기(Assembler)가 수행


#의존방법 명시 하는 세가지 방법 정리

1. 생성자를 통한 초기화

-스프링에서의 객체생성은 bean
-스프링의 객체는 무조건 싱글톤(객체 하나 이상 생성 안함)

<bean id="userImpl" class="di.demo1.UserImpl"> // id 는 객체명
 <constructor-arg value="30" /> // constructor : 생성자
 <constructor-arg value="+" />
 <constructor-arg value="15" />
</bean>

<bean id="userService1" class="di.demo1.UserService">
 <constructor-arg>
  <ref bean="userImpl"/> // ref : reference 객체
 </constructor-arg>
</bean>

-객체 생성 및 의존관계 설정 다른 쉬운 방법
<bean id="userService1" class="di.demo1.UserService">
 <constructor-arg ref="userImpl"/>
</bean>
 
2. 프로퍼티를 통한 객체생성

-setter 필요
-인자가 없는 생성자(default)를 부름
-인자가 없는 생성자가 없으면 오류 

<bean id="userImpl" class="di.demo1.UserImpl">
 <property name="num1" value="15" />
 <property name="num2" value="20" />
 <property name="oper" value="*" />
</bean>

<bean id="userService1" class="di.demo1.UserService">
 <property name="user" ref="userImpl" />
 <property name="user">
  <ref bean="userImpl"/>
 </property>
</bean>

3. XML 네임스페이스

-setter 필요

<bean id="userImpl" class="di.demo1.UserImpl"
 p:num1="15"
 p:num2="7"
 p:oper="/"/> 

<bean id="userService1" class="di.demo1.UserService"
  p:user-ref="userImpl"/>