๐นย ์ ๋ฆฌ by ์ฅ๋ฏธ(https://velog.io/@newbiekim/)
์คํ๋ง์ ์๋ฐ ์ธ์ด ๊ธฐ๋ฐ์ ํ๋ ์์ํฌ์ด๋ฉฐ, ๊ฐ์ฒด ์งํฅ ์ธ์ด๊ฐ ๊ฐ์ง ๊ฐ๋ ฅํ ํน์ง์ ์ด๋ ค๋ธ๋ค. ์ฆ, ์คํ๋ง์ ์ข์ ๊ฐ์ฒด ์งํฅ ์ ํ๋ฆฌ์ผ์ด์ ์ ๊ฐ๋ฐํ ์ ์๊ฒ ๋์์ฃผ๋ ํ๋ ์์ํฌ๋ค.
์์กด์ฑ ์ฃผ์ (DI)๊ณผ ์ ์ด ์ญ์ (IoC), ๊ด์ ์งํฅ ํ๋ก๊ทธ๋๋ฐ(AOP) ์์๋ฅผ ํตํด **๋์จํ ๊ฒฐํฉ(Loose Coupling)**์ ๋ฌ์ฑํ ์ ์๊ฒ ํด์ค๋ค. ์ด๋ ๊ฒ ๋์จํ ๊ฒฐํฉ์ผ๋ก ๊ฐ๋ฐํ ์ ํ๋ฆฌ์ผ์ด์ ์ ๋จ์ ํ ์คํธ๋ฅผ ์ํํ๊ธฐ ์ฉ์ดํ๋ค๋ ์ฅ์ ์ด ์๋ค.
์์กด์ฑ ์ฃผ์ (DI, Dependency Injection)
โฌ๏ธย DI๋ฅผ ์ฌ์ฉํ์ง ์์ ์ฝ๋์ ๊ฒฝ์ฐ
@RestController
public class NoDIController {
private MyService service = new MyServiceImpl();
@GetMapping("/hello")
public String getHello() {
return service.getHello();
}
}
Controller๋ โMyServiceโ ๊ฐ์ฒด์ ์์กดํ๊ฒ ๋๋ค.
๊ฐ์ฒด์ ์ธ์คํด์ค๋ฅผ ์ป๊ฒ ๋๋ฉด ๊ฐ์ฒด ๊ฐ์ ๊ฒฐํฉ๋๊ฐ ์ฌ๋ผ๊ฐ๊ณ , ์ด๋ฐ ์ฝ๋ ์์ฑ์ ๋จ์ ํ ์คํธ๋ฅผ ์ํด Mock ๊ฐ์ฒด(๊ฐ์ง ๊ฐ์ฒด)๋ฅผ ์ฌ์ฉํ ์ ์๊ฒ ๋๋ค.
โฌ๏ธย DI๋ฅผ ์ฌ์ฉํ ์ฝ๋์ ๊ฒฝ์ฐ
@Service
public class MyServiceImpl implements MyService {
@Override
public String getHello() {
return "Hello";
}
}
@RestController
public class DIController {
MyService myService;
@Autowired
public DIController(MyService myService) {
this.myService = myService;
}
@GetMapping("/hello")
public String getHello() {
return myService.getHello();
}
}
@Service
, @Autowired
์ด๋
ธํ
์ด์
์ ํตํด MyService์ ์ธ์คํด์ค๋ฅผ ๊ฐ์ง๋ค.
์์ ๊ฐ์ด ์ฝ๋๋ฅผ ์์ฑํ๋ฉด ๋จ์ ํ ์คํธ ์ํฉ์์ Service ๊ฐ์ฒด๋ฅผ Mock ๊ฐ์ฒด๋ก ๋์ฒดํ์ฌ ์ฝ๊ฒ ํ ์คํธ ํ ์ ์๋ค.
๊ด์ ์งํฅ ํ๋ก๊ทธ๋๋ฐ(AOP, Aspect Oriented Programming)