스프링 애플리케이션에서는 오브젝트의 생성과 관계설정, 사용, 제거 등의 작업을 애플리케이션 코드 대신 독립된 컨테이너
가 담당한다. 이를 컨테이너가 코드 대신 오브젝트에 대한 제어권을 갖고 있다고 해서 IoC
라고 부른다. 그래서 스프링 컨테이너를 IoC 컨테이너
라고도한다.
스프링 컨테이너는 단순한 DI 작업 보다 더 많은 일을 하는데, DI를 위한 빈 팩토리를 구현하며 애플리케이션을 개발하는 데 필요한 여러 가지 컨테이너 기능을 추가한 것을 Application Context
라고 부른다.
BeanFactoryPostProcessors
가 호출되고 빈의 설정정보에 대한 후처리가 진행된다BeanPostProcessor
가 호출되고 빈 객체에 대한 후처리를 진행애플리케이션 컨텍스트를 상속하는 구현체
RootApplicationContext
Servlet Context(servlet-context.xml)
web.xml 을 통한 구성
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/beans.xml</param-value>
</context-param>
...
</web-app>
ContextLoaderListener
: RootApplicationContext를 생성하는 클래스<context-param>
태그 내부 contextConfigLocation 설정파일을 읽어 RootApplicationContext를 생성한다.<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
...
<!-- Processes application requests -->
<servlet>
<servlet-name>spring-web-app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-web-app</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
<servlet>
태그 내부 contextConfigLocation 설정파일(sertvlet-context.xml)을 읽어 servlet-context를 생성하이브리드 구성 ⇒ XmlWebApplicationContext
public class XmlWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException {
XmlWebApplicationContext context = new XmlWebApplicationContext();
context.setConfigLocation("/WEB-INF/beans.xml");
ServletRegistration.Dynamic dispatcher = container
.addServlet("dispatcher", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
WebApplicationInitializer
인터페이스 구현onStartup
메서드를 재정의 (Configuration 파일 등록)자바를 통한 구성 ⇒ AnnotationConfiWebgApplicationInitializer
public class AnnotationConfigWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(container);
context.register(ConfigurationComponentScan.class);
context.refresh();
ServletRegistration.Dynamic dispatcher = container
.addServlet("dispatcher", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
Spring Boot