IOC 란? (자료 : 백기선)
Inversion of Control
의존성에 대한 컨트롤이 바뀌었다는 뜻.
개발자가 의존 객체를 직접 만드는 것(New를 이용)이 아닌, 외부에서 주입 받아 사용하는 방법을 뜻한다.
IOC 컨테이너
스프링은 IOC을 제어하는 Container를 제공
ApplicationContext가 즉 IOC Contianer라고 할 수있음.
주 역할은 Bean으로 등록된 객체들의 의존성을 주입해줌.
이로 인하여 의존성이 주입된 객체들은 NullPointException이 발생하지 않음.
아래와 같이 테스트 시 정상 수행.
1
2
3
4
5
6
7
8
9
|
@Autowired
ApplicationContext applicationContext;
@Test
public void testDI() {
SampleController bean = applicationContext.getBean(SampleController.class);
assertThat("bean").isNotNull();
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
Bean
IOC CONTAINER가 관리하는 객체들은 BEAN이라고 부름.
빈은 기본적으로 싱글톤 패턴으로 관리됨.
Bean 등록하는 방법은 크게 두가지임.
1. Component Scan 방식
컴포넌트 Scan 방식은 설정한 최상단 패키지부터 Component Scan 어노테이션이 붙어 있는 객체들을 클래스들을 찾아 Bean으로 등록한다.
예시 @ :) @Component, @Service, @Repository, @Controller, @Configruation
전자정부 프레임워크에서는 dispatcher-servlet에서 아래와 같이 컴포넌트 스캔을 설정함.
1
2
3
4
5
6
7
8
9
10
|
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Service" />
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Repository" />
</context:component-scan>
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
2. 직접 등록
자바로 Bean을 등록하는 방식과 XML로 Bean을 등록하는 방식이 있는데, 현재는 주로 자바단에서 Bean을 등록하는 것을 더 많이 사용한다고 한다.
자바 - @Configuration이 붙어 있는 클래스를 작성해야 하며, @Bean 어노테이션을 이용하여 Bean을 등록한다.
1
2
3
4
5
6
7
8
9
10
11
|
@Configuration
public class SampleConfig {
@Bean
public SampleController sampleController() {
return new SampleController();
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
XML 방식 -
1
2
3
4
5
6
7
|
<!-- 타일즈 뷰 설정 -->
<property name="viewClass"
<property name="order" value="1" />
</bean>
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|