programing tip

web.xml을 사용하여 Spring에서 컨텍스트로드

itbloger 2020. 11. 7. 09:04
반응형

web.xml을 사용하여 Spring에서 컨텍스트로드


Spring MVC 애플리케이션에서 web.xml을 사용하여 컨텍스트를로드 할 수있는 방법이 있습니까?


봄 문서에서

Spring은 Java 기반 웹 프레임 워크에 쉽게 통합 될 수 있습니다. 당신이 할 필요가 선언하는 것입니다 의 ContextLoaderListener를 당신의 web.xml을 하고 사용 는 contextConfigLocation을 부하에 세트로하는 컨텍스트 파일을.

<context-param>:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

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

그런 다음 WebApplicationContext를 사용하여 빈에 대한 핸들을 가져올 수 있습니다.

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");

자세한 내용은 http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html참조 하십시오.


현재 클래스 경로에 상대적으로 컨텍스트 위치를 지정할 수도 있습니다.

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext*.xml</param-value>
</context-param>

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

서블릿 자체를 정의하는 동안 컨텍스트를로드 할 수도 있습니다 ( WebApplicationContext ).

  <servlet>
    <servlet-name>admin</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
                /WEB-INF/spring/*.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>admin</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

( ApplicationContext ) 보다는

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

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

또는 둘 다 함께 할 수 있습니다.

WebApplicationContext를 사용하는 것의 단점은 DispatcherServlet위에서 언급 한 메서드와 마찬가지로 여러 진입 점 (예 : Webservice Servlet, REST servlet등)에 대해 컨텍스트가로드되는 이 특정 Spring 진입 점 ( )에 대해서만 컨텍스트를로드한다는 것입니다 .

에 의해로드 된 ContextLoaderListener컨텍스트는 실제로 DisplacherServlet에 대해 특별히로드 된 컨텍스트의 상위 컨텍스트입니다. 따라서 기본적으로 애플리케이션 컨텍스트에서 모든 비즈니스 서비스, 데이터 액세스 또는 저장소 Bean을로드하고 컨트롤러를 분리하고 WebApplicationContext에 대한 해석기 Bean을 볼 수 있습니다.

참고URL : https://stackoverflow.com/questions/6451377/loading-context-in-spring-using-web-xml

반응형