โ
Dependency injection
๊ฐ์ฒด๊ฐ ์ง์ ํ์ํ ๊ฐ์ฒด๋ฅผ ์์ฑํ์ง ์๊ณ , ์ธ๋ถ์์ ํ์ํ ๊ฐ์ฒด๋ฅผ ์ฃผ์
๋ฐ์ ์ฌ์ฉํ๋ค.
์คํ๋ง์ DI๋ฅผ ํตํด ํด๋์ค ๊ฐ์ ๊ฒฐํฉ๋๋ฅผ ๋ฎ์ถ๊ณ , ํ
์คํธ ๊ฐ๋ฅ์ฑ๊ณผ ์ ์ง๋ณด์์ฑ์ ํฅ์์ํจ๋ค.
โ ์์กด์ฑ ์ฃผ์ ์ 3๊ฐ์ง ๋ฐฉ์
@Autowired๋ฅผ ํ์ฉํ ์์กด์ฑ ์ฃผ์
๋ฐฉ์์ ๋ค์ ์ธ ๊ฐ์ง์
๋๋ค:โ
@AutoWired
์์ฑ์๊ฐ ์ฌ๋ฌ๊ฐ์ผ ๋ ๋น์ ๋ฑ๋กํ ์์ฑ์๋ฅผ ์ ํํ๊ฒ ๋๋ค.
final๋ก ์ ์ธ๋์ด ๋ถ๋ณ์ฑ์ ์ ์งํ ์ ์์ผ๋ฉฐ, ์ํ ์ฐธ์กฐ๋ฅผ ์ ํ๋ฆฌ์ผ์ด์
์์ ์์ ์ ํ์ธํ ์ ์์ด ๊ฐ์ฅ ๊ถ์ฅ๋๋ ๋ฐฉ์์
๋๋ค.@Controller
public class DemoController {
private final DemoService demoService;
public DemoController(DemoService demoService) {
this.demoService = demoService;
}
}
@Controller
public class DemoController {
@Autowired
private DemoService demoService;
}
@Controller
public class DemoController {
private DemoService demoService;
@Autowired
public void setDemoService(DemoService demoService) {
this.demoService = demoService;
}
}
๐ค ์ ์์ฑ์ ์ฃผ์ ์ ๊ถ์ฅํ ๊น?
์คํ๋ง์์๋ ์์ฑ์ ์ฃผ์ ์ ๊ฐ์ฅ ๊ถ์ฅํฉ๋๋ค. ๊ทธ ์ด์ ๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค:
์ํ ์ฐธ์กฐ ๋ฐฉ์ง: ์ ํ๋ฆฌ์ผ์ด์ ์คํ ์์ ์ ์ํ ์ฐธ์กฐ๋ฅผ ์กฐ๊ธฐ์ ๊ฐ์งํ ์ ์์ต๋๋ค.
๋ถ๋ณ์ฑ ๋ณด์ฅ: ์์กด ๊ฐ์ฒด๋ฅผ final๋ก ์ ์ธํ์ฌ ๋ณ๊ฒฝ์ ๋ง์ ์ ์์ต๋๋ค.
ํ ์คํธ ์ฉ์ด์ฑ: ์์ฑ์๋ฅผ ํตํด ์์กด์ฑ์ ์ฃผ์ ๋ฐ๊ธฐ ๋๋ฌธ์ ํ ์คํธ ์ ์์กด ๊ฐ์ฒด๋ฅผ ๋ช ์์ ์ผ๋ก ์ ๋ฌํ ์ ์์ต๋๋ค.
โ
ํ
์คํธ์์ DI์ ์ฅ์
์์ฑ์ ์ฃผ์
์ ์ฌ์ฉํ๋ฉด DI ์ปจํ
์ด๋ ์์ด๋ ํ
์คํธ๊ฐ ๊ฐ๋ฅํฉ๋๋ค. ํ์ํ ์์กด ๊ฐ์ฒด๋ฅผ ์ง์ ์ฃผ์
ํ์ฌ POJO ๋ฐฉ์์ผ๋ก ํ
์คํธํ ์ ์์ผ๋ฉฐ, ์ด๋ ํ
์คํธ์ ๊ฒฉ๋ฆฌ์ฑ๊ณผ ์ฌํ์ฑ์ ๋์ฌ์ค๋๋ค.
public class DemoServiceTest {
@Test
public void testDoSomething() {
DemoRepository repo = new DemoRepository();
DemoService service = new DemoService(repo);
service.doSomething();
}
}
โ๏ธ ์์กด์ฑ ์ฃผ์ ๋ฐฉ์ ๋น๊ต
| ๋ฐฉ์ | ์ฅ์ | ๋จ์ |
|---|---|---|
| ์์ฑ์ ์ฃผ์ | ๋ถ๋ณ์ฑ ๋ณด์ฅ, ์ํ ์ฐธ์กฐ ๋ฐฉ์ง, ํ ์คํธ ์ฉ์ด | ์ฃผ์ ๋ฐ์ ๊ฐ์ฒด๊ฐ ๋ง์์ง์๋ก ์์ฑ์๊ฐ ๊ธธ์ด์ง |
| ํ๋ ์ฃผ์ | ์ฝ๋๊ฐ ๊ฐ๊ฒฐํ๊ณ ๋น ๋ฅด๊ฒ ์์ฑ ๊ฐ๋ฅ | ํ ์คํธ ๋ฐ ์ ์ง๋ณด์ ์ด๋ ค์, ์ธ๋ถ ๋ณ๊ฒฝ ๋ถ๊ฐ |
| ์์ ์ ์ฃผ์ | ๋ฐํ์ ์ ์์กด์ฑ ๋ณ๊ฒฝ ๊ฐ๋ฅ | public setter ํ์๋ก ์ธํด ์บก์ํ ์ ํด |
beanFactory