[Spring] μ€νλ§ IOC 컨ν μ΄λμ Bean
π Spring IOC, Container, DI, Bean?
μ€νλ§μ μ¬μ©νλ€ λ³΄λ©΄ κΎΈμ€ν λ€μ΄μ€λ μ©μ΄λ€μ΄λ€. μ΄ μ₯μμλ κ·Έ κ°λ μ λν΄μ μμλ³΄κ³ μ λ¦¬ν΄ λ³Έλ€.
IOC (Inversion of Control)
μ μ΄μ μμ μ΄λΌ λΆλ₯Έλ€. μλμμ 컨ν μ΄λμ ν¨κ» μ€λͺ νλ€.
Container (컨ν μ΄λ)
컨ν μ΄λλ λ³΄ν΅ κ°μ²΄μ μλͺ μ£ΌκΈ°, μμ±λ μΈμ€ν΄μ€λ€μκ² μΆκ°μ μΈ κΈ°λ₯μ μ 곡νλ€. μ€νλ§ μ»¨ν μ΄λλ μμ‘΄μ±λ κ΄λ¦¬νλ€.
Spring IOC Container - μ€νλ§ IOC 컨ν μ΄λ
μ€νλ§μ μ€νλ§ IOC 컨ν μ΄λμμ κ°μ²΄λ₯Ό κ΄λ¦¬νλλ°, μ΄λ μ€νλ§μ΄ μ μ΄ κΆνμ κ°μ Έ κ°μ²΄ μμ±, κ΄κ³, μμ‘΄μ±, μλͺ μ£ΌκΈ° κ΄λ¦¬ νλλ° μ΄λ μμ±λ κ°μ²΄λ₯Ό Beanμ΄λΌκ³ νλ€. μ΄ Beanλ€μ μ±κΈν€μΌλ‘ κ΄λ¦¬λλ€.
μ¦, κ°λ°μλ μ΄λ° κ³Όμ μ μ€ν΅ ν¨μΌλ‘μ¨ λΉμ¦λμ€ λ‘μ§μ μ§μ€ν μ μκ² λλ€.
κ·Έλ λ€λ©΄ μ°λ¦¬κ° λ§λ ν΄λμ€λ₯Ό μ€νλ§ IOC 컨ν μ΄λκ° κ΄λ¦¬ν μ μκ² νλ €λ©΄ μ΄λ»κ² ν κΉ? λ°λ‘ BeanμΌλ‘ λ±λ‘ν΄ μ£Όλ©΄ λλ€. BeanμΌλ‘ λ±λ‘νλ λ°©λ²μ μ¬λ¬ κ°μ§ λ°©λ²μ΄ μλλ° μμ μ μ¬μ©νλ XMLμ ν΅ν΄ λ±λ‘νλ λ°©λ²μ μ μΈνκ³ μ΄λ Έν μ΄μ μ ν΅ν΄ λ±λ‘νλ 2κ°μ§ λ°©λ²μ νμΈν΄ 보μ.
1. BeanμΌλ‘ λ±λ‘νλ λ°©λ²
1-1. Component Scan
BeanμΌλ‘ λ±λ‘λ μ€λΉκ° λ ν΄λμ€λ€μ μ€μΊνμ¬ BeanμΌλ‘ λ±λ‘ν΄ μ£Όλ κ³Όμ μ΄λ€.
μ€λΉκ° λ ν΄λμ€λ€μ΄λ @Component μ΄λ Έν μ΄μ μ ν΄λμ€μ μΆκ°ν κ²μ λ§νλ€. λ§μ΄ μ¬μ©νλ @Controller, @Service, @Repositoryλ λ°λΌκ° 보면 @Componetμ΄ μλ κ±Έ νμΈν μ μλ€.
κ·Έλ λ€λ©΄ μ΄μ νλ λ κΆκΈμ¦μ΄ μκΈ΄λ€. λλ μ»΄ν¬λνΈ μ€μΊμ ν μ μ΄ μλλ° μ μμ μ΄λ Έν μ΄μ λ§ λΆμμ λΏμΈλ° BeanμΌλ‘ λ±λ‘λ κ±ΈκΉ?
μ€νλ§λΆνΈ νλ‘μ νΈλ₯Ό μμ±νλ©΄ κΈ°λ³Έμ μΌλ‘ ~Application ν΄λμ€κ° μμ±λλλ° μ΄ ν΄λμ€μλ @SpringBootApplication μ΄λ Έν μ΄μ μ΄ μλλ° κ·Έ μμ μ΄ν΄λ³΄λ©΄ @ComponentScan μ΄λ Έν μ΄μ μ ν΅ν΄μ ν΄λΉ ν΄λμ€λ₯Ό κΈ°μ€μΌλ‘ νμ ν¨ν€μ§λ₯Ό μ€μΊνλ κ±Έ μ μ μλ€.
1-2. Java config - @Configuration, @Bean
@Configuration ν΄λμ€μμ @Bean μ΄λ Έν μ΄μ μ μ¬μ©ν΄ μλμΌλ‘ μ€νλ§ μ»¨ν μ΄λμ λΉμ λ±λ‘νλ λ°©λ²μ΄λ€.
@Configuration
public class TestConfig {
@Bean
public OpenApi openApi() {
return new OpenApi();
}
}
μμ κ°μ΄ μλμΌλ‘ Beanμ λ±λ‘νλ κ²½μ°μλ μ£Όλ‘ λ€μκ³Ό κ°μ λ μ¬μ©νλ€.
1. κ°λ°μκ° μ§μ μ μ΄κ° λΆκ°λ₯ν λΌμ΄λΈλ¬λ¦¬λ₯Ό λΉμΌλ‘ λ±λ‘νμ¬ μ¬μ©ν λ
2. μ λ²μμ μΌλ‘ μ¬μ©λλ ν΄λμ€λ₯Ό λ±λ‘ν λ
3. λ€νμ±μ νμ©νμ¬ μ¬λ¬ ꡬν체λ₯Ό λ±λ‘ν΄μ£Όμ΄μΌ ν λ
2. DI(Dependency Injection) - μμ‘΄μ± μ£Όμ
BeanμΌλ‘ λ±λ‘νκ³ μ€νλ§ IOC 컨ν μ΄λμ μν΄ μμ±λ λμλ€λ©΄, μ΄μ μμ‘΄μ± μ£Όμ μ ν΅ν΄ μ¬μ©ν μ μλλ° μμ‘΄μ± μ£Όμ μλ μ¬λ¬ κ°μ§ λ°©λ²μ΄ μλ€. μ°¨λ‘λλ‘ νμΈν΄ 보μ.
2-1. νλ μ£Όμ
@Controller
public class TestController {
@Autowired
private TestService testService;
}
2-2. μμ μ(Setter) μ£Όμ
@Controller
public class TestController {
private TestService testService;
@Autowired
public void setTestService(TestService testService) {
this.testService = testService;
}
}
2-3. μμ±μ μ£Όμ
@Controller
public class TestController {
private final TestService testService;
public TestController(TestService testService) {
this.testService = testService;
}
}