ContextLoaderListener 를 사용 하여 응용 프로그램 Context 만 들 기

ContextLoaderListener 를 사용 하여 applicationContext 를 만 들 때 서버 가 listener 를 지원 해 야 합 니 다.아래 서버 들 은 모두 Li stener 를 지원 합 니 다.이 서버 를 사용 하면 ContextLoaderListener 를 사용 하여 applicationContext 인 스 턴 스 를 만 들 수 있 습 니 다.
Apache Tomcat4.x+ 。Jetty 4.x+。Resin2.1.8+。Orion 2.0.2+。BEAWebLogic8.1SP3。
Spring 은 SeryletContextListener 의 구현 클래스 ContextLoaderListener 를 제공 합 니 다.이 종 류 는 listener 로 사용 할 수 있 습 니 다.생 성 할 때 WEB-INF/아래 applicationContext.xrnl 파일 을 자동 으로 찾 습 니 다.따라서 하나의 프로필 만 있 고 파일 이름 이 applicationContext.xrnl 이 라면 웹 xrnl 파일 에 다음 코드 를 추가 하면 됩 니 다.
<1istener>
<listener-class>org.springframework.web.context.ContextLoaderListener</
listener-class></listener>

여러 개의 프로필 을 불 러 올 필요 가 있다 면,여러 프로필 이 있 는 웹 xrnl 파일 은 다음 과 같 습 니 다.
 <!--XML       --〉
<?xml version="l.O"encoding="i80-8859-1"?>
<1-- web.xm1 DTD --〉<!DOCTYPE web-appPUBLIC
"-//Sun Microsystems.i c.//DTDWeb Application 2.3//
EN"''http://java.sun.com/dtd/web-app_2_3.dtd''><web-app>
<!-- >
<context-param><1-- contextConfigLocation…〉
<param-name>contextConfigLocation</param-name>
<!-- , --〉
<param-value>/WEB-iNF/daoContext.xml./WEB-INF/application
Context.xml</param-value></context-param><!--
listener ApplicationContext -->
<listener>
<listener-class>org.springframework.web.context.ContextLoader
Listener</listener-class></listener></web-app>

contextConfigLocation 에서 설정 파일 을 지정 하지 않 으 면 Spring 은 applicationContext.xrnl 설정 파일 을 자동 으로 찾 습 니 다.contextConfigLocation 가 있 으 면 이 매개 변 수 를 이용 하여 설정 파일 을 확인 합 니 다.이 매개 변 수 는 지정 한 문자열 입 니 다.Spring 의 ContextLoaderListener 는 이 문자열 을 여러 개의 프로필,쉼표",","빈 칸","및 분점"으로 분해 합 니 다.문자열 의 분할 문자 로 사용 할 수 있 습 니 다.
applicationContext.xrnl 파일 도 없고 contextConfigLocation 매개 변 수 를 사용 하여 프로필 을 확인 하지 않 았 거나 contextConfigLocation 에서 확 정 된 프로필 이 존재 하지 않 습 니 다.Spring 에서 프로필 을 불 러 올 수 없 거나 applicationContext 인 스 턴 스 를 정상적으로 만 들 수 없습니다.
 
Spring 은 bean 정의 에 따라 웹 응용 프로그램 Context 대상 을 만 들 고 웹 응용 프로그램의 ServletContext 에 저장 합 니 다.대부분의 경우 응용 프로그램 중의 bean 은 응용 프로그램 Context 의 존 재 를 느 낄 필요 가 없고 응용 프로그램 Context 의 JoC 만 이용 하면 된다.
응용 프로그램 에서 applicationContext 인 스 턴 스 를 가 져 올 필요 가 있다 면 다음 과 같은 방법 으로 가 져 올 수 있 습 니 다.
 WebApplicationContextctx:
WebApplicationContextUtils.getWebApplicationContext(servletContext);

다음은 Servlet 을 사용 하여 applicationContext 의 전체 소스 코드 를 가 져 옵 니 다.
public class SpringTestServlet extends HttpServlet
//Servlet 。
public voidservice(HttpServletRequestrequest,HttpServletResponse response)
throwsServletExceptio , java.io.IOException
// Servlet ServletContext
ServletContext sc = getServletContext();
// WebApplicationContextUtils ApplicationContext
WebApplicationContext ctx =WebApplicationContextUtils.
getWebApplicationContext(sc);
// Servlet
PrintWriter out = response.getWriter();
// ApplicationContext
out.println(ctx);

프로그램 에서 applicationContext 대상 을 수 동 으로 가 져 온 다음 Servlet 에 직접 출력 할 수 있 습 니 다.applicationContext 를 보고 웹 xml 파일 에서 지정 한 두 개의 프로필 을 불 러 옵 니 다.
 
 
From: http://book.51cto.com/art/200808/87215.htm

좋은 웹페이지 즐겨찾기