반응형
스프링 IoC 컨테이너의역할
- 빈 인스턴스 생성
- 의존 관계 설정
- 빈 제공
(IoC 예시)
객체를 내가 직접 new 생성 (IoC 적용 x)
class OwnerController{
private OwnerRepository repository = new OwnerRepository();
}
IoC 를 이용한 의존성 주입 (IoC 적용 o)
class OwnerController{
private OwnerRepository repo;
public OwnerController(OwnerRepository repo){ //생성자를 통해 매개변수로 객체를 받는다
this.repo = repo;
}
}
IoC OwnerRepository라는 의존성을 OwnerController 에게 주입시킨다. -> 이것이 IoC 이다.
class OwnerControllerTest{
@Test
public void create(){
OwnerRepository repo = new OnwerRepository(); //OwnerRepository객체를 생성해서
OwnerController controller = new OnwerController(repo);//OwnerController객체에 의존성 주입
}
}
DI (Dependency Injection) 의존성 주입 예
ApplicationContext
- ClassPathXmlApplicationContext( XML )
- AnnotationConfigApplicationContext( Java )
빈 설정
- 빈 명세서
- 빈에 대한 정의를 담고 있다.
- 이름
- 클래스
- 스코프
- 생성자 아규먼트 (constructor)
- 프로퍼트 (setter)
- ....
컴포넌트 스캔
- 설정 방법
- XML 설정에서는 context:component-scan
- 자바 설정에서 @ComponentScan
- xml 설정파일에 다음 코드를 추가해야한다.
<context:component-scan base-package = "com.application.demo">
com.application.demo 라는 package에 있는 bean을 *스캔하여 등록하겠다 라는 뜻.
*Scanning을 할때에는 어노테이션을 확인하고 bean으로 자동으로 등록해준다.
@SpringBootApplication
@SpringBootAplication는 auto-configuration을 담당한다.
@SpringBootApplication 하나만으로 @EnableAutoConfiguration, @ComponentScan, @Configuration 세 가지 Annotation을 사용한 것과 같은 동작을 할 수 있다.
- 특정 패키지 이하의 모든 클래스 중에 @Component 애노테이션을 사용한 클래스를 빈으로 자동으로 등록해줌.
반응형