웹곡뷰/μŠ€ν”„λ§

DI(Dependency Injection) - 객체 생성을 μ–΄λ””μ„œ μ–΄λ–»κ²Œ ν•˜λŠλƒ

이노킀_ 2021. 7. 6. 08:59

μŠ€ν”„λ§ ν”„λ ˆμž„μ›Œν¬μ—μ„œλŠ” Container(IoC)λ₯Ό λ§Œλ“€μ–΄ 놓고, κ·Έ μ•ˆμ—μ„œ 객체(bean)λ₯Ό μƒμ„±ν•˜μ—¬ ν™œμš©ν•œλ‹€. 

ν•„μš”ν•  λ•Œλ§ˆλ‹€ 객체λ₯Ό μƒμ„±ν•˜λŠ” 것이 μ•„λ‹ˆλΌ λ¦¬μ†ŒμŠ€μ—μ„œ 객체λ₯Ό κΊΌλ‚΄ μ‚¬μš©ν•œλ‹€κ³  μƒκ°ν•˜λ©΄ λœλ‹€. 

 

Bean을 μƒμ„±ν•˜λŠ” 방법 

1. 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"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

	<bean id="tWalk" class="testPjt.TransportationWalk"/>
</beans>
public class MainClass {
	public static void main(String[] args)
	{
		//1. κΈ°μ‘΄ μžλ°” 방법
		TransportationWalk tw = new TransportationWalk();
		tw.move();	
		
		//2. xml μ‚¬μš© 방법
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:appConfig.xml");
		TransportationWalk tw2 = ctx.getBean("tWalk", TransportationWalk.class);
		tw2.move();
		
		ctx.close();
	}
}

DI λΌλŠ” 컨셉은 μŠ€ν”„λ§μ˜ 고유 κΈ°λŠ₯은 μ•„λ‹ˆλ‹€. 

객체λ₯Ό λ…λ¦½ν™”ν•΄μ„œ ν™•μž₯&μœ μ§€λ³΄μˆ˜ μš©μ΄ν•˜κ²Œ κ°œλ°œκ°€λŠ₯ν•˜κ²Œ ν•˜λ„λ‘ ν•˜λŠ” 객체지ν–₯ 개발 방법 쀑에 ν•˜λ‚˜μž„.

-> μœ μ—°ν•΄μ§

 

DI 기법

1. μƒμ„±μžμ—μ„œ μ£Όμž…(new)

2. setterμ—μ„œ μ£Όμž…

3. μƒμ„±μžμ—μ„œ λ””ν΄νŠΈλ‘œ μ£Όμž…ν•œ ν›„, setterλ₯Ό μ΄μš©ν•˜μ—¬ λ³€κ²½ κ°€λŠ₯ν•˜κ²Œ 함.