복붙노트

[SPRING] Spring에서 ContextLoaderListener의 역할 / 목적은 무엇입니까?

SPRING

Spring에서 ContextLoaderListener의 역할 / 목적은 무엇입니까?

내 프로젝트에서 사용되는 Spring Framework를 배우고 있습니다. web.xml 파일에 ContextLoaderListener 항목이 있습니다. 그러나 그것이 개발자에게 얼마나 도움이되는지를 알 수는 없습니까?

ContextLoaderListener의 공식 문서에서 WebApplicationContext를 시작한다고합니다. WebApplicationContext 관련 JavaDocs는 다음과 같이 말합니다.

그러나 내부적으로 WebApplicationContext를 초기화하는 ContextLoaderListener를 사용하여 달성하고자하는 것을 이해할 수 없습니까?

내 이해에 따라 ContextLoaderListener는 Spring 구성 파일 (web.xml의 contextConfigLocation에 지정된 값)을 읽고 구문 분석하고 해당 구성 파일에 정의 된 싱글 톤 Bean을로드합니다. 비슷하게 prototype bean을로드하고자 할 때, 우리는 그것을로드하기 위해 동일한 웹 어플리케이션 컨텍스트를 사용할 것입니다. 그래서 우리는 ContextLoaderListener로 웹 애플리케이션을 초기화하여 미리 설정 파일을 읽고 / 구문 분석 / 검증하고 의존성을 주입 할 때마다 지체없이 바로 수행 할 수 있습니다. 이 이해가 맞습니까?

해결법

  1. ==============================

    1.귀하의 이해가 정확합니다. ApplicationContext는 Spring 빈이 사는 곳이다. ContextLoaderListener의 목적은 두 가지입니다.

    귀하의 이해가 정확합니다. ApplicationContext는 Spring 빈이 사는 곳이다. ContextLoaderListener의 목적은 두 가지입니다.

    ContextLoaderListener에 대한 또 다른 편리한 점은 WebApplicationContext를 작성하고 WebApplicationContext가 ServletContextAware Bean과 getServletContext 메소드를 통해 ServletContext에 대한 액세스를 제공한다는 것입니다.

  2. ==============================

    2.ContextLoaderListener는 선택 사항입니다. 여기서 한 가지만 강조하면 ContextLoaderListener를 설정하지 않고 Spring 애플리케이션을 부팅 할 수있다. DispatcherServlet을 가진 최소한의 web.xml 만있다.

    ContextLoaderListener는 선택 사항입니다. 여기서 한 가지만 강조하면 ContextLoaderListener를 설정하지 않고 Spring 애플리케이션을 부팅 할 수있다. DispatcherServlet을 가진 최소한의 web.xml 만있다.

    다음과 같이 보입니다.

    을 포함한다.

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
        xsi:schemaLocation="
            http://java.sun.com/xml/ns/javaee 
            http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
        id="WebApp_ID" 
        version="2.5">
      <display-name>Some Minimal Webapp</display-name>
      <welcome-file-list>   
        <welcome-file>index.jsp</welcome-file>    
      </welcome-file-list>
    
      <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>
          org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
      </servlet-mapping>
    </web-app>
    

    dispatcher-servlet.xml 파일을 작성하고 WEB-INF 아래에 저장하십시오. 환영 목록에서 index.jsp에 대해 언급 했으므로이 파일을 WEB-INF 아래에 추가하십시오.

    dispatcher-servlet.xml

    dispatcher-servlet.xml에서 bean을 정의합니다.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans 
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd     
            http://www.springframework.org/schema/context     
            http://www.springframework.org/schema/context/spring-context.xsd">
    
        <bean id="bean1">
          ...
        </bean>
        <bean id="bean2">
          ...
        </bean>         
    
        <context:component-scan base-package="com.example" />
        <!-- Import your other configuration files too -->
        <import resource="other-configs.xml"/>
        <import resource="some-other-config.xml"/>
    
        <!-- View Resolver -->
        <bean 
            id="viewResolver" 
            class="org.springframework.web.servlet.view.UrlBasedViewResolver">
          <property 
              name="viewClass" 
              value="org.springframework.web.servlet.view.JstlView" />
          <property name="prefix" value="/WEB-INF/jsp/" />
          <property name="suffix" value=".jsp" />
        </bean>
    </beans>
    
  3. ==============================

    3.간단한 Spring 애플리케이션의 경우 web.xml에 ContextLoaderListener를 정의 할 필요가 없습니다. 모든 Spring 설정 파일을 에 넣을 수 있습니다 :

    간단한 Spring 애플리케이션의 경우 web.xml에 ContextLoaderListener를 정의 할 필요가 없습니다. 모든 Spring 설정 파일을 에 넣을 수 있습니다 :

    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/mvc-core-config.xml, classpath:spring/business-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    

    복잡한 DispatcherServlet을 정의한보다 복잡한 Spring 애플리케이션의 경우 ContextLoaderListener에 정의 된 모든 DispatcherServlet에서 공유하는 공통 Spring 구성 파일을 가질 수있다.

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/common-config.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <servlet>
        <servlet-name>mvc1</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/mvc1-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet>
        <servlet-name>mvc2</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/mvc2-config.xmll</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    

    ContextLoaderListener는 루트 응용 프로그램 컨텍스트에 대한 실제 초기화 작업을 수행합니다.

    나는이 기사가 많은 도움이되는 것을 발견했다. Spring MVC - 애플리케이션 컨텍스트와 웹 애플리케이션 컨텍스트

  4. ==============================

    4.블로그 인 "ContextLoaderListener - Spring MVC의 목적"은 아주 좋은 설명입니다.

    블로그 인 "ContextLoaderListener - Spring MVC의 목적"은 아주 좋은 설명입니다.

    이에 따르면 Application-Context는 계층 구조이므로 DispatcherSerlvet의 컨텍스트는 ContextLoaderListener 컨텍스트의 자식이됩니다. 이로 인해 컨트롤러 레이어 (Struts 또는 Spring MVC)에서 사용되는 기술은 루트 컨텍스트에서 생성 된 ContextLoaderListener와는 독립적 일 수 있습니다.

  5. ==============================

    5.Servlet 파일을 기본 이름 지정 규칙 [servletname] -servlet.xml 및 Web-INF / 아래의 경로 대신 사용자 정의 위치 또는 사용자 정의 이름으로 넣으려면 ContextLoaderListener를 사용할 수 있습니다.

    Servlet 파일을 기본 이름 지정 규칙 [servletname] -servlet.xml 및 Web-INF / 아래의 경로 대신 사용자 정의 위치 또는 사용자 정의 이름으로 넣으려면 ContextLoaderListener를 사용할 수 있습니다.

  6. ==============================

    6.ContextLoaderListner는 모든 다른 구성 파일 (서비스 계층 구성, 지속성 계층 구성 등)을 단일 스프링 응용 프로그램 컨텍스트로로드하는 서블릿 수신기입니다.

    ContextLoaderListner는 모든 다른 구성 파일 (서비스 계층 구성, 지속성 계층 구성 등)을 단일 스프링 응용 프로그램 컨텍스트로로드하는 서블릿 수신기입니다.

    이렇게하면 여러 XML 파일에서 스프링 구성을 분리하는 데 도움이됩니다.

    컨텍스트 파일이로드되면 Spring은 Bean 정의를 기반으로 WebApplicationContext 객체를 생성하고이를 웹 애플리케이션의 ServletContext에 저장합니다.

  7. ==============================

    7.기본적으로 ContextLoaderListener를 사용하여 루트 응용 프로그램 컨텍스트와 웹 응용 프로그램 컨텍스트를 분리 할 수 ​​있습니다.

    기본적으로 ContextLoaderListener를 사용하여 루트 응용 프로그램 컨텍스트와 웹 응용 프로그램 컨텍스트를 분리 할 수 ​​있습니다.

    컨텍스트 매개 변수로 매핑 된 구성 파일은 루트 응용 프로그램 컨텍스트 구성으로 작동합니다. 디스패처 서블릿으로 매핑 된 구성 파일은 웹 응용 프로그램 컨텍스트처럼 작동합니다.

    모든 웹 애플리케이션에서 우리는 여러 개의 디스패처 서블릿을 가질 수 있으므로 여러 웹 애플리케이션 컨텍스트가있을 수 있습니다.

    그러나 모든 웹 응용 프로그램에는 모든 웹 응용 프로그램 컨텍스트와 공유되는 루트 응용 프로그램 컨텍스트가 하나만있을 수 있습니다.

    루트 애플리케이션 컨텍스트에서 공통 서비스, 엔티티, 측면 등을 정의해야합니다. 그리고 컨트롤러, 인터셉터 등은 관련된 웹 어플리케이션 컨텍스트에 있습니다.

    샘플 web.xml은

    <!-- language: xml -->
    <web-app>
    
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <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>example.config.AppConfig</param-value>
        </context-param>
        <servlet>
            <servlet-name>restEntryPoint</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextClass</param-name>
                <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
            </init-param>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>example.config.RestConfig</param-value>
            </init-param>       
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>restEntryPoint</servlet-name>
            <url-pattern>/rest/*</url-pattern>
        </servlet-mapping>
        <servlet>
            <servlet-name>webEntryPoint</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextClass</param-name>
                <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
            </init-param>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>example.config.WebConfig</param-value>
            </init-param>       
            <load-on-startup>1</load-on-startup>
        </servlet>  
        <servlet-mapping>
            <servlet-name>webEntryPoint</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
    </web-app> 
    

    여기서 config 클래스 example.config.AppConfig는 다른 모든 웹 응용 프로그램 컨텍스트와 공유 할 루트 응용 프로그램 컨텍스트의 서비스, 엔티티, 애스펙트 등을 구성하는 데 사용할 수 있습니다 (예를 들어 RestConfig 및 WebConfig라는 두 개의 웹 응용 프로그램 컨텍스트 구성 클래스가 있음)

    추신 : 여기서 ContextLoaderListener는 완전히 선택 사항입니다. 여기서 web.xml에 ContextLoaderListener를 언급하지 않으면 AppConfig가 작동하지 않습니다. 이 경우 WebConfig 및 Rest Config에 모든 서비스 및 엔티티를 구성해야합니다.

  8. ==============================

    8.웹 응용 프로그램 배포 시간에 실행하려는 일부 코드를 집어 넣을 수있는 포인트를 제공합니다.

    웹 응용 프로그램 배포 시간에 실행하려는 일부 코드를 집어 넣을 수있는 포인트를 제공합니다.

  9. ==============================

    9.이 부트 스트랩 리스너는 Spring의 루트 WebApplicationContext를 시작하고 종료하는 것입니다. 웹 애플리케이션은 여러 디스패처 서블릿을 가질 수 있고 각각 컨트롤러, 뷰 해석기, 핸들러 매핑 등을 포함하는 자체 애플리케이션 컨텍스트를 가질 수 있습니다. 그러나 서비스 응용 프로그램 컨텍스트에서 서비스 bean, DAO bean을 원할 수 있으며 모든 하위 응용 프로그램 컨텍스트 디스패처 서블릿에 의해 생성 된 애플리케이션 컨텍스트).

    이 부트 스트랩 리스너는 Spring의 루트 WebApplicationContext를 시작하고 종료하는 것입니다. 웹 애플리케이션은 여러 디스패처 서블릿을 가질 수 있고 각각 컨트롤러, 뷰 해석기, 핸들러 매핑 등을 포함하는 자체 애플리케이션 컨텍스트를 가질 수 있습니다. 그러나 서비스 응용 프로그램 컨텍스트에서 서비스 bean, DAO bean을 원할 수 있으며 모든 하위 응용 프로그램 컨텍스트 디스패처 서블릿에 의해 생성 된 애플리케이션 컨텍스트).

    이 청취자의 두 번째 용도는 봄 보안을 사용하고자 할 때입니다.

  10. ==============================

    10.귀하의 이해가 정확합니다. ContextLoaderListener에서 왜 어떤 장점이 보이지 않는지 궁금합니다. 예를 들어, 데이터베이스를 관리하기 위해 세션 팩토리를 빌드해야합니다. 이 작업은 다소 시간이 걸릴 수 있으므로 시작할 때 수행하는 것이 좋습니다. 물론 init 서블릿이나 다른 것을 사용하여 할 수 있지만, Spring의 접근법의 장점은 코드를 작성하지 않고 구성하는 것입니다.

    귀하의 이해가 정확합니다. ContextLoaderListener에서 왜 어떤 장점이 보이지 않는지 궁금합니다. 예를 들어, 데이터베이스를 관리하기 위해 세션 팩토리를 빌드해야합니다. 이 작업은 다소 시간이 걸릴 수 있으므로 시작할 때 수행하는 것이 좋습니다. 물론 init 서블릿이나 다른 것을 사용하여 할 수 있지만, Spring의 접근법의 장점은 코드를 작성하지 않고 구성하는 것입니다.

  11. ==============================

    11.우리가 ContextLoaderListener없이 web.xml을 작성하면 봄 보안에서 customAuthenticationProvider를 사용하여 액션을 줄 수 없다. DispatcherServelet은 ContextLoaderListener의 자식 컨텍스트이므로 customAuthenticationProvider는 ContextLoaderListener 인 parentContext의 일부입니다. 따라서 부모 컨텍스트는 하위 컨텍스트의 종속성을 가질 수 없습니다. 따라서 spring-context.xml을 initparam에 쓰는 대신 contextparam에 작성하는 것이 가장 좋습니다.

    우리가 ContextLoaderListener없이 web.xml을 작성하면 봄 보안에서 customAuthenticationProvider를 사용하여 액션을 줄 수 없다. DispatcherServelet은 ContextLoaderListener의 자식 컨텍스트이므로 customAuthenticationProvider는 ContextLoaderListener 인 parentContext의 일부입니다. 따라서 부모 컨텍스트는 하위 컨텍스트의 종속성을 가질 수 없습니다. 따라서 spring-context.xml을 initparam에 쓰는 대신 contextparam에 작성하는 것이 가장 좋습니다.

  12. ==============================

    12.나는 그 실제 사용이 하나 이상의 설정 파일을 갖고 싶거나 예를 들어 applicationcontext.xml 대신에 xyz.xml 파일을 가지고 있다고 믿는다.

    나는 그 실제 사용이 하나 이상의 설정 파일을 갖고 싶거나 예를 들어 applicationcontext.xml 대신에 xyz.xml 파일을 가지고 있다고 믿는다.

    contextConfigLocation /WEB-INF/training-service.xml, /WEB-INF/training-data.xml

    ContextLoaderListener에 대한 또 다른 접근법은 아래와 같이 ContextLoaderServlet을 사용하는 것입니다.

    컨텍스트 org.springframework.web.context.ContextLoaderServlet 1

  13. ==============================

    13.리스너 클래스 - 이벤트를 수신합니다 (예 : 서버 시작 / 종료).

    리스너 클래스 - 이벤트를 수신합니다 (예 : 서버 시작 / 종료).

    ContextLoaderListener -

  14. ==============================

    14.ContextLoaderListener의 스프링 프레임 워크 목적에서는 응용 프로그램의 백엔드를 구동하는 중간 계층 및 데이터 계층 구성 요소와 같은 다른 Bean을 응용 프로그램에로드하는 것이 있습니다.

    ContextLoaderListener의 스프링 프레임 워크 목적에서는 응용 프로그램의 백엔드를 구동하는 중간 계층 및 데이터 계층 구성 요소와 같은 다른 Bean을 응용 프로그램에로드하는 것이 있습니다.

  15. from https://stackoverflow.com/questions/11815339/role-purpose-of-contextloaderlistener-in-spring by cc-by-sa and MIT license