☘️ Spring

[Spring] Day59 - 의존관계 주입 (DI)

harveydent 2023. 8. 1. 16:43
728x90

의존관계 주입

의존관계 주입이란 Dependency Injection의 약자로 객체 간의 의존성을 외부로부터 주입하여 객체의 결합도를 낮추고 유연성을 높이는 디자인 패턴입니다. 이 패턴은 객체가 필요로 하는 의존성을 직접 생성하지 않고, 외부에서 생성된 의존성을 주입하여 사용하게 됩니다.

의존성

의존성(Dependency)이란 한 객체가 다른 객체를 사용하거나 참조할 때 그 객체들 사이의 관계를 말합니다. 예를 들어, 클래스 A가 클래스 B의 기능을 사용하거나 클래스 B의 인스턴스를 필요로 할 때 A는 B에 의존성이 있습니다.

 

의존관계 주입 방법

  1. 생성자 주입(Constructor Injection)
  2. Setter 주입(Setter Injection)

1. 생성자 주입

생성자 주입은 객체를 생성할 때 해당 객체가 필요로 하는 의존성을 생성자를 통해 주입하는 방식입니다. 객체가 생성될 때 필요한 모든 의존성을 강제로 제공받게 되므로 객체의 일관성과 불변성을 유지하기 용이합니다. 또한 생성자 주입을 사용하면 필수적인 의존성을 강제할 수 있어서 빠뜨릴 가능성이 줄어듭니다.

2. Setter 주입

Setter 주입은 의존성을 설정하는 Setter 메서드를 통해 의존성을 주입하는 방식입니다. 객체 생성 후에도 의존성을 변경할 수 있어서 동적인 의존성 변경이 필요한 상황에 유용합니다. 그러나 생성자 주입과는 달리, 필수적인 의존성을 보장하기 어렵고, 의존성 누락이나 변경을 놓칠 수 있는 문제가 발생할 수 있습니다.

 

실습

applicationContext.xml

스프링 프레임워크에서 설정 정보는 기술하는 파일인 applicationContext.xml에서 빈(Bean)을 생성하고 관리합니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

	<context:component-scan base-package="day59" />

	<context:component-scan base-package="test" />
	<bean class="test.GalaxyWatch" id="watch" />
	<bean class="test.MiWatch" id="watch" />
	

	<bean class="test.GalaxyPhone" id="galaxy">
		<constructor-arg ref="mw" />
	</bean>
	
	<bean class="test.GalaxyWatch" id="gw" lazy-init="true" />
	<bean class="test.MiWatch" id="mw" lazy-init="true" />
	
	<bean class="test.IPhone" id="apple">
		<property name="watch" ref="gw" />
		<property name="name" value="티모" />
	</bean>
 
	<bean class="day59.SamsungTV" id="tv">
		<constructor-arg ref="a" />
	</bean>
	
	<bean class="day59.LgTV" id="tv">
		<property name="remote" ref="a" />
	</bean>
	
	<bean class="day59.RemoteA" id="a" />
	<bean class="day59.RemoteB" id="b" />

	<bean class="day59.TestBean" id="tb">
		<property name="testList">
			<list>
				<value>작은 티모</value>
				<value>중간 티모</value>
				<value>큰 티모</value>
			</list>
		</property>
	</bean>
	<bean class="day59.TestBean2" id="tb2">
		<property name="testMap">
			<map>
				<entry>
					<key><value>1001</value></key>
					<value>작은 티모</value>
				</entry>
				<entry>
					<key><value>1002</value></key>
					<value>중간 티모</value>
				</entry>
				<entry>
					<key><value>1003</value></key>
					<value>큰 티모</value>
				</entry>
			</map>
		</property>
	</bean>
</beans>

applicationContext.xml

GitHub

https://github.com/Qkrwnsgus0522/Spring

 

GitHub - Qkrwnsgus0522/Spring

Contribute to Qkrwnsgus0522/Spring development by creating an account on GitHub.

github.com

 

728x90