DI (Dependency Injection)
๐ ๊ฐ์
- DI๋ ํ์ํ ์์กด ๊ฐ์ฒด๋ฅผ
new
๋ก ์ง์ ๋ง๋ค์ง ์๊ณ ์ธ๋ถ(์ปจํ ์ด๋) ์์ ์ฃผ์ ๋ฐ์ ์ฌ์ฉํ๋ ๋ฐฉ์์ด๋ค. - Spring์์ IoC ์ปจํ ์ด๋(ApplicationContext) ๊ฐ ๋น์ ์์ฑ/๊ด๋ฆฌํ๊ณ , ์์ฑ์ยท์ธํฐยทํ๋ ๋ฑ ๋ค์ํ ๋ฐฉ๋ฒ์ผ๋ก ์์กด์ฑ์ ์ฃผ์ ํ๋ค.
- IoC ๋ฅผ ๊ตฌํํ๋ ํต์ฌ ๋ฉ์ปค๋์ฆ์ด DI์ด๋ฉฐ, ๊ตฌ์ฑ/ํ๊ฒฝ์ external-configuration/auto-configuration์ผ๋ก ์ ์ฐํ๊ฒ ๋ฐ๊ฟ ์ ์๋ค.
โ๐ป ํ์ค ์์ฝ
DI๋ ๊ฐ์ฒด ๊ฐ ์ฐ๊ฒฐ ์ฑ ์์ ์ฝ๋์์ ์ปจํ ์ด๋๋ก ๋ถ๋ฆฌํด ๊ฒฐํฉ๋โยทํ ์คํธ ์ฉ์ด์ฑโ๋ฅผ ๋ง๋๋ ์์กด์ฑ ์ฐ๊ฒฐ ๋ฐฉ์์ด๋ค.
๐ค ์ ํ์ํ๊ฐ?
- ๊ตฌํ ๊ต์ฒด/ํ์ฅ ์ฉ์ด: ์ธํฐํ์ด์ค ๊ธฐ๋ฐ์ผ๋ก ๊ตฌํ ๋ฐ๊ฟ ๋ผ์ฐ๊ธฐ ์ฌ์
- ํ ์คํธ ์์ฐ์ฑโ: ๋ชฉ/์คํ ๋ฑ ํ ์คํธ ๋์ญ ์ฃผ์ ์ด ๊ฐ๋จ
- ํ๊ฒฝ ๋ถ๋ฆฌ ์ฉ์ด: ํ๋กํ/์กฐ๊ฑด์ ๋ฐ๋ผ ๋น ์ ํ ๊ฐ๋ฅ
- ๊ด์ฌ์ฌ ๋ถ๋ฆฌ: ์ธ๋ถ ๋ฐ ์๋ ๊ตฌ์ฑ์ ์ค์ (properties), ๋น์ฆ๋์ค ๋ก์ง์ ์ฝ๋
์ฃผ์ ๋ฐฉ์ & ์ ํ
- ์์ฑ์ ์ฃผ์
(๊ถ์ฅ): ๋ถ๋ณ์ฑ ์ ์ง, NPE ์๋ฐฉ, ํ
์คํธ/๋ฆฌํฉํ ๋ง์ ์ต์ . ๋จ์ผ ์์ฑ์๋ฉด
@Autowired
์๋ต. - ์ธํฐ ์ฃผ์ : ์ ํ์ ์์กด์ฑ, ๋ฐํ์ ๊ต์ฒด๊ฐ ํ์ํ ๊ฒฝ์ฐ. (์ธํฐ๋ฅผ ๊ณต๊ฐํด์ผ ํ๋ฏ๋ก ๋จ์ฉ ๊ธ์ง)
- ํ๋ ์ฃผ์ (์ง์): ์บก์ํ/๋ถ๋ณ์ฑ ์ ํด, ํ ์คํธ ์ด๋ ค์(๋ฆฌํ๋ ์ ํ์). ๋ ๊ฑฐ์/์ํ ์ธ ์ฌ์ฉ ๋น๊ถ์ฅ.
๊ถ์ฅ ์์: ์์ฑ์ ์ฃผ์ > ์ธํฐ ์ฃผ์ > ํ๋ ์ฃผ์ (์ง์).
๐ง ์์
(A) ์์ฑ์ ์ฃผ์ - ๊ถ์ฅ โ
@Component
public class Communicator {
private final Greeting greeting;
private final Farewell farewell;
private final Sender sender;
// ๋จ์ผ ์์ฑ์ โ @Autowired ์๋ต ๊ฐ๋ฅ
public Communicator(Greeting greeting, Farewell farewell, Sender sender) {
this.greeting = greeting;
this.farewell = farewell;
this.sender = sender;
}
}
Lombok ์ฌ์ฉ
@RequiredArgsConstructor
@Component
public class Communicator {
private final Greeting greeting;
private final Farewell farewell;
private final Sender sender;
}
(B) ์ธํฐ ์ฃผ์
@Component
public class AppStartupRunner implements ApplicationRunner {
private Greeting greeting;
@Autowired
public void setGreeting(Greeting greeting) {
this.greeting = greeting;
}
@Override
public void run(ApplicationArguments args) {
greeting.sayHello();
}
}
์ฃผ์ ๋ฐ๊ณ ์ถ์ ๊ฐ์ฒด๋ฅผ ์ ์ธํ๊ณ , Setter ๋ฅผ ์ด์ฉํด ์์กด์ฑ์ ์ฃผ์ ํ๋ค.
(C) ํ๋ ์ฃผ์ - ์ง์ โ
@Component
public class AppStartupRunner implements ApplicationRunner {
@Autowired
private Greeting greeting; // ์ง์
@Override
public void run(ApplicationArguments args) {
greeting.sayHello();
}
}
๐ ๊ด๋ จ
- IoC : DI๋ IoC๋ฅผ ๊ตฌํํ๋ ์๋จ
- auto-configuration - ๊ธฐ๋ณธ ๋น ์๋ ๋ฑ๋ก
- external-configuration - ํ๊ฒฝ/ํ๋กํ ๊ธฐ๋ฐ ์ค์ ๋ถ๋ฆฌ