Request session scoped bean 사용하기

From JCFWiKi

Jump to: navigation, search

그림:check.gif

  • 산출물 : JCF3.0™ - Spring Configuration 가이드
  • 작성자: ;박동영
  • 작성일 : 2008/06/17
  • 버전 : 1.0
  • 개정이력 :

Copyright © 2007 Daewoo Information Systems Co., Ltd.


그림:warning.gif

스프링 빈의 스코프는 기본값으로 싱글톤이다. 하지만 설정하기에 따라서 프로토타입이나 웹 애플리케이션의 리퀘스트, 세션과 생명을 같이 하는 빈으로 설정할 수도 있다.

여기서는 웹 애플리케이션에서 이용할 수 있는 리퀘스트 및 세션 스코프 빈을 이용하는 방법을 설명한다.

이를 위해서 할 일의 개요는 아래와 같다.

1. Jar 라이브러리 확인

2. 웹 애플리케이션 디스크립터 설정

3. 스프링 설정파일에 빈 추가 및 참조 설정


리퀘스트나 세션 스코프 빈을 이용하기 위해서는 스프링 2.5 이상을 이용하여야 한다. 그리고 프록시 기능을 이용하기 때문에 CGLIB의 도움을 받아야 한다.

그림:warning.gif

스프링 문서상으로는 인터페이스를 중심으로 프로그램했을 경우는 자바 프록시도 사용 가능하다고 하지만, 2.5.1에서 테스트했을 때는 작동하지 않았었다.


웹 애플리케이션의 request나 session의 라이프사이클과 같이 해야하기 때문에 라이프사이클 이벤트에 대한 리스너가 필요하다. 이를 위한 클래스를 웹 애플리케이션의 필터나 리스너에 등록해주어야 한다.

보통 리퀘스트/세션 스코프 빈은 다른 빈 (보통 싱글톤 빈)의 프로퍼티로서 일생을 살아가도록 하게 된다. 이 때 프로퍼티로 해당 클래스를 직접 연결해서는 안되고 프록시를 통해서 연결해주어야 한다. 왜냐하면 스프링 애플리케이션 컨텍스트가 초기화될 때 빈의 프로퍼티 세팅이 끝나기 때문이다. 리퀘스트나 세션 스코프 빈의 클래스 인스턴스가 직접 들어가게서는 안되고, 각각의 세션이나 리퀘스트별 인스턴스로 라우팅해줄 수 있는 프록시가 중간에 개입할 필요가 있는 것이다.

유효한 빈 스코프 값들

Scope Description
singleton Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.


리퀘스트/세션 스코프 세팅된 빈 이용하기

예를 들면 세션 로깅을 위한 함수가 있는데, 서블릿 리퀘스트의 애트리뷰트나 세션 값을 필요로할 경우, 스트러츠의 액션 클래스로부터 호출되는 각 클래스의 메소드마다 해당 변수를 물고 가는 번거로움을 피하고자 할 경우 이러한 스코프 빈을 이용하면 좋다.

사용할 때는 일반적인 빈 처럼 인젝션하여 사용하면 된다.

해당 리퀘스트 스코프 또는 세션 스코프에서는 같은 빈 인스턴스를 바라보고 있으므로 빈에 적당한 값을 넣기도 하고 조회하기도 하면서 쓰면 된다.


덧) 일일이 스프링 설정 파일에 인젝션 설정을 하기 귀찮을 경우

별도의 유틸리티 클래스를 두어, 이를 스프링 빈으로 설정하고 스코프 빈을 멤버 변수로 가지고 가도록 하여 인젝션 설정을 하고, 해당 빈에 대한 get/set 메소드를 퍼블릭 스태틱 메소드로 선언해준다.


1. Jar 라이브러리 확인

  • cglib-nodep-2.1_3.jar 추가
  • spring-2.5.x.jar



2. 웹 애플리케이션 디스크립터 설정

그림:information.gif

빈의 스코프를 조작하기 위해 웹애플리케이션에 트리거할 수 있는 후크를 설치

servlet 2.4인 경우 listener를 이용하고, servlet 2.3인 경우 filter를 이용한다.


<web-app>
  ...
  <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>
  ...
</web-app>
<web-app>
  ..
  <filter> 
    <filter-name>requestContextFilter</filter-name> 
    <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
  </filter> 
  <filter-mapping> 
    <filter-name>requestContextFilter</filter-name> 
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  ...
</web-app>


3. 스프링 설정파일에 빈 추가 및 참조 설정

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
    <!-- a HTTP Session-scoped bean exposed as a proxy -->
    <bean id="userPreferences" class="com.foo.UserPreferences" scope="session">
          
          <!-- this next element effects the proxying of the surrounding bean -->
<aop:scoped-proxy/>
</bean>
   <!-- a singleton-scoped bean injected with a proxy to the above bean -->
   <bean id="userService" class="com.foo.SimpleUserService">
       <!-- a reference to the proxied 'userPreferences' bean -->
       <property name="userPreferences" ref="userPreferences"/>
   </bean>
</beans>