ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스프링 IOC 컨테이너 연동
    SPRING/스프링 MVC 2021. 6. 5. 18:16

    pom.xml에 의존성 추가

     <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>5.3.7</version>
     </dependency>

     

    ContextLoaderListener 등록

     

    contextLoaderListenr 역할

    - ApplicationContext를 서블릿 어플리케이션 생명주기에 맞춰서 바인딩해준다.

      - ApplicationContext를 웹어플리케이션에 등록된 서블릿들이 사용할 수 있도록 서블릿 컨텍스트에 등록해준다.

      - 서블릿이 종료될때 제거해준다.

      - 즉, ApplicationContext를 연동해준다.

      - 서블릿에서 IoC 컨테이너를 ServletContext를 통해 꺼내 사용할 수 있다.

      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
    

     

    ApplicationContext 생성

    -  xml도 많이  사용하지만, 최근에는 Java설정파일을 많이 사용한다.

    -  아래는 Spring IOC container를 사용하는 방법이지, Spring MVC까지 사용한 것은 아니다.

    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
      </context-param>
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.springmvc.AppConfig</param-value>
      </context-param>

     

    @Configuration
    @ComponentScan
    public class AppConfig {
    
    }
    
    public class HelloServlet extends HttpServlet {
    
        @Override
        public void init() throws ServletException {
            // 서블릿 생성 (처음 한번마 실행)
            System.out.println("init");
        }
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("doGet");
    
            ApplicationContext context = (ApplicationContext) getServletContext()
                    .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);;
            HelloService helloService = context.getBean(HelloService.class);
    
            resp.getWriter().write("Hello Servlet " + helloService.getName());
        }
    
        @Override
        public void destroy() {
            System.out.println("destroy");
        }
    
    }
    
    @Service
    public class HelloService {
    
        public String getName() {
            return "jumpDeveloper";
        }
    
    }
    

     

    'SPRING > 스프링 MVC' 카테고리의 다른 글

    스프링 MVC -WEB.XML 제거  (0) 2021.06.10
    DispatchServlet 분석  (0) 2021.06.06
    스프링 MVC 연동  (0) 2021.06.06
    서블릿 리스너와 필터  (0) 2021.06.05
    Spring MVC란?  (0) 2021.06.02
Designed by Tistory.