Notice
Recent Posts
Recent Comments
Link
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Tags
more
Archives
Today
Total
관리 메뉴

노승현

DI 의존성 주입이란? 본문

Spring

DI 의존성 주입이란?

nsh95 2024. 2. 28. 08:35

팩토리 패턴 != 싱글톤 패턴

 

싱글톤을 유지하기 위해 사용하는 것이 팩토리 패턴

 

예시 코드에서, 싱글톤 유지가 안된게 맞다.

코드에 new 가 작성되어있다면 틀릴 위험이 있다.

중프 코드에서는, 싱글톤 유지 o

 

applicationContext.xml

<beans>

<bean class=“test.IPhone”  scope=“prototype” /> // 사용자마다 핸드폰을 주고 싶다면 

<bean class=“GalaxyPhone”/>

</beans>

 

------------------------------------------------------------------------------------------------

 

[IoC 를 배울 때 함께 알아야 하는 개념]

 

 

(1) DI 란?

Dependency Injection

의존 주입

개발자 -> 스프링 컨테이너(Spring 프레임 워크)

1. 객체를 생성(new) 및 관리(호출 시 해당 객체 메서드 수행)

2. 의존 주입

 

(2) 의존성이란? 

어떤 메서드를 수행할 때

다른 객체를 미리 new 해야하는 상황

 

 

1. 생성자 주입(Constructor Injection)

2번 방식보다 더 강제성이 짙음

생성자 주입할 때 에러가 발생하면 해당 객체는 생성 되지 않음 == 필수적일 때 사용하는 방식

 

applicationContext.xml

<beans>

	<bean class=“test.IPhone”>

		<constructor-args ref=“gw” />// 생성자 주입 해주는 태그

	</bean>



	<bean class=“test.AppleWatch” id=“aw” lazy-init=“true”/> // 선택 됐을 때만 로드될 수 있게

	<bean class=“test.GalaxyWatch” id=“gw” lazy-init=“true”/>



	<bean class=“test.GalaxyPhone”>

		<constructor-args ref=“galaxyWatch” />

	</bean>

</beans>

applicationContext.xml

<beans>

<bean class=“test.IPhone”>

<constructor-args ref=“gw” />// 생성자 주입 해주는 태그

</bean>

 

<bean class=“test.AppleWatch” id=“aw” lazy-init=“true”/> // 선택 됐을 때만 로드될 수 있게

<bean class=“test.GalaxyWatch” id=“gw” lazy-init=“true”/>

 

<bean class=“test.GalaxyPhone”>

<constructor-args ref=“galaxyWatch” />

</bean>

</beans>

 

2. Setter 주입(Setter Injection)

1번의 방식보다 덜 강제적임

기본 생성자 + setter 를 활용 하므로 기본 생성자를 반드시 필요로 함

applicationContext.xml

<beans>

	<bean class=“test.IPhone”>

		<property name=“watch” ref=“gw” /> // property 속성 멤버변수 attribute 다 같은 뜻

		<property name=“userName” value=“홍길동” />

	</bean>

	<bean class=“test.AppleWatch” id=“aw” />

	<bean class=“test.GalaxyWatch” id=“gw” />



	<bean class=“test.GalaxyPhone”>

		<property name=“watch” ref=“gw” />

	</bean>

</beans>

 

 

applicationContext.xml

<beans>

	<bean class=“test.TestBean”>

		<property name=“testList”>

			<list>

				<value>홍길동</value>

				<value>임꺽정</value>

				<value>아무무</value>

			</list>

		</property>
	


		<property name=“testMap”>

			<map>

				<entry>

					<key><value>홍길동</value></key>

					<value>미드</value>

				</entry>



				<entry>

					<key><value>임꺽정</value></key>

					<value>원딜</value>

				</entry>



				<entry>

					<key><value>아무무</value></key>

					<value>정글</value>

				</entry>

			</map>

		</property>

	</bean>

</beans>

 

 

~~추가 해줘라고 한다면 인터페이스를 만들어라

무엇이든 들어갈 수 있도록 타입을 인터페이스로 맞춰라

그런다음 넣고 싶은 애를 넣으면 완성

'Spring' 카테고리의 다른 글

DBCP  (0) 2024.03.05
Spring MVC ver.2 로 변환하기  (1) 2024.03.05
ASPECT 란?  (1) 2024.03.04
Spring 파일 생성 및 흐름 이해  (2) 2024.02.28
Spring 이란?  (1) 2024.02.27