Arthur's Blog

DI(Dependency Injection)๋ž€? ๋ณธ๋ฌธ

OOP

DI(Dependency Injection)๋ž€?

Leeseojune53 2023. 7. 1. 00:34

๐Ÿ“Œ ์ •์˜

์˜์กด์„ฑ ์ฃผ์ž…์ด๋ผ๊ณ  ๋งํ•˜๋ฉฐ, ์ถ”์ƒํ™”๋ฅผ ํ•ด์น˜์ง€ ์•Š๊ณ  ์˜์กด์„ฑ์„ ์ธ์ˆ˜๋กœ ๋„˜๊ฒจ์ฃผ๋Š” ๊ฒƒ์„ ๋งํ•œ๋‹ค.

๐Ÿ˜Ž ์˜ˆ์‹œ

Spring Boot๋ฅผ ์˜ˆ์‹œ๋กœ ๋“ค์ž๋ฉด, Service ๊ตฌํ˜„์ฒด์—์„œ๋Š” Repository์™€ ๊ฐ™์ด ์˜์กด์„ฑ์„ ๊ฐ–๋Š”๋‹ค. ํ•˜์ง€๋งŒ ํ•ด๋‹น Service๋ฅผ ์ถ”์ƒํ™” ํ•œ interface๋Š” Repository๊ฐ€ ์ธ์ˆ˜๋กœ ๋„˜์–ด๊ฐ€๋Š” ์ •๋ณด๋ฅผ ์ „ํ˜€ ๋‹ด๊ณ ์žˆ์ง€ ์•Š๋‹ค.

interface UserService {
    void removeUser(Long userId);
}
 
@Service
@RequiredArgsConstructor
class UserServiceImpl implements UserService {
    private final UserRepository userRepository;
}
 
 

์œ„ ์ฝ”๋“œ๋Š” ์œ„์˜ ๋ง์— ๋”ฐ๋ผ์„œ UserServiceImpl์˜ ์ถ”์ƒํ™” ๊ฐ์ฒด์ธ UserService์—๋Š” UserRepository์˜ ์ •๋ณด๋ฅผ ์ „ํ˜€ ๋‹ด๊ณ  ์žˆ์ง€์•Š์€ ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

โš  ์ฃผ์˜์ 

์—ฌ๊ธฐ์„œ ์ฐฉ๊ฐํ•˜๋Š” ๋ถ€๋ถ„์€ ๋‚ด๊ฐ€ ์œ„์—์„œ ์„ค๋ช…ํ•œ ๊ฒƒ์„ ๋ณด๊ณ  DI๋ฅผ ๊ตฌํ˜„ํ•˜๋ ค๋ฉด interface๋ฅผ ๊ผญ ๊ฐ€์ ธ์•ผ ํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

์—ฌ๊ธฐ์„œ ํ˜ผ๋™ํ•  ์ˆ˜ ์žˆ๋Š” ๊ฐœ๋…์ด DIP(Dependency Injection Principle)์ธ๋ฐ DIP์™€๋Š” ๋ช…๋ฐฑํ•˜๊ฒŒ ๋‹ค๋ฅธ ๊ฒƒ์ด๋‹ค. ์ž์„ธํ•œ ๋‚ด์šฉ์€ DI vs IoC vs DIP๋ฅผ ์ฐธ๊ณ ํ•ด์ฃผ์„ธ์š”!