본문 바로가기
Spring

[Spring] 04. 의존성 주입

by ssunooo 2024. 10. 2.

 

 

의존성과 주입의 정의

의존성 : 코드 수행 시 다른 코드 필요성 확인

 

의존성 구조의 애플리케이션

 

1. 라이브러리

2. CDN

3. JAR 

4. bean

 

주입 : 의존하는 코드 내용을 추가

 

 

의존성 주입( DI )의 종류

1. 생성자 주입( CI ) 

 

- 의존주입대상이 중요한(불가피한) 상황에 사용
- 의존주입대상 생성자 먼저 호출 후 생성자 호출
- 의존주입대상이 생성오류 발생하면 프로그램 종료

- 높은 의존도

 

생성자 주입(CI)

 

<constructor-arg>를 사용해 bean 참조를 통한 의존성 주입

GalaxyPhone은 GalaxyWatch에 대해 의존성을 가짐

 

<생성자 주입 코드>

<?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">
   
   <bean class="test.GalaxyPhone" id="samsung">
   		<constructor-arg ref="sw"/>
   </bean>
   
   <bean class="test.GalaxyWatch" id="sw"></bean>
   
</beans>


2. Setter 주입( SI )

 

- 웹개발 시 보편적으로 사용
- 기본생성자 먼저 호출( setter 호출 )
- 의존주입대상이 생성오류 발생해도 프로그램 종료 x

- 낮은 의존도

 

getter,setter 추가

 

getter,setter 생성 후 setter 주입 bean 추가

 

setter 주입(SI)

 

<property>를 사용해 bean 참조를 통한 의존성 주입

IPhone은 AppleWatch에 대해 의존성을 가짐

 

<Setter 주입 코드>

<?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">
   
   <bean class="test.IPhone" id="apple">
   		<property name="watch" ref="aw"/>
   		<property name="num" value="1234"/>
   </bean>
   		
   <bean class="test.AppleWatch" id="aw"></bean>
   
</beans>

 

 

의존성 주입에서의 Service단의 역할

 

class = 액션명

 

property = 멤버변수

name = DAO명

 

 

2024.10.02