SessionScope Bean ?
* 빈(Bean)을 정의할 때 SessionScope로 정의할시, Session영역 생성시점에(Browser에서 서버로 최초요청 발생) @SessionScope로 정의된 Bean객체가 주입되며 이후 요청이 발생하여도 Bean객체는 재 주입되지 않는다.
(주입객체는 브라우저가 종료되기 전까지 같은 주소값을 가지며 해당 객체에 데이터 저장유지 및 공유된다)
* 빈(Bean)이 주입되는 방법만 정의되는 것이며, Session영역에 빈(Bean)이 저장되지는 않는다.
* 빈(Bean)을 등록하는 방법으로 Java의 @SessionScope 어노테이션 활용 또는, Xml의 <bean/> 정의시 scope="session" 속성을 지정하는 방법이 있다.
# @RequestScope: 새로운 요청이 발생될 때마다 Bean주입되며 새로운 인스턴스가 할당되므로 객체주소값이 바뀐다.
SessionScope Bean Exercise..
-- Java 설정.
1. 빈 등록을 위한, 클래스선언 (SessionScope)
* SessionBean1, SessionBean2, SessionBean3, SessionBean4 클래스 선언 (세션스코프)
[SessionBean1, SessionBean2] : 클래스 선언 -> @Configuration, @Bean, @SessionScope 사용하여 빈 수동등록
[SessionBean3, SessionBean4] : @Component, @ComponentScan, @SessionScope 사용하여 빈 자동등록
@Component사용시, @ComponentSacn에 스캔할 컴포넌트의 패키지(Package)경로를 등록해야 한다.
2. RootAppContext, ServletAppContext 수정 - 빈 등록
* SessionBean1, SessionBean2, SessionBean3, SessionBean4 빈 등록
[SessionBean1, SessionBean2] : @Configuration, @Bean을 사용하여 수동으로 빈 수동등록.
[SessionBean3, SessionBean4] : @ComponentSacn("컴포넌트 스캔경로") 를 선언함으로써 컴포넌트 스캔을 통한 @Component 선언된 클래스 빈(Bean) 자동등록.
* [SessionBean2, SessionBean4] 클래스타입이 아닌 설정 빈 이름으로 주입.
--> SessionBean2: @Bean("빈 이름: sessionBean2")
SessionBean4: @Component(value="빈 이름: sessionBean4")
3. TestSessionScopeBeanController 컨트롤러 생성
* @Autowired, @Resource 어노테이션을 사용하여 @SessionScope로 생성되는 빈(Bean)을 주입을 받아 사용할 수 있다.
-- @Autowired : 클래스 타입을 통하여, 객체를 주입받는다 (SessionBean1, SessionBean3)
-- @Resource : 빈 생성시 설정했던 이름으로 주입받는다. (SessionBean2, SessionBean4)
선언형식은 @Resource(name="빈 이름")와 같다.
* @SessionScope는 빈(Bean)이 주입되는 방법만 정의되는 것이며, Session영역에 빈(Bean)이 저장되지는 않는다. 따라서, Request영역(Model, ModelAndView)에 저장하여 빈(Bean) 활용이 가능하다.
3. SesscionScopeBean 확인 (Browser 테스트)
* 최초 서블릿요청 ("/sessionBeanTest1") 발생시 SessionScope로 정의된 빈(Bean) @Autowired, @Resource를 통한 객체주입 및 Setter를 통한 데이터저장 이후, 서블릿 재 요청 ("/sessionBeanTest1/result") 에서 위, SessionScope 저장된 객체에 관하여 Getter를 통하여 이전요청시 저장된 데이터 확인.
* Session영역 생성시점에(Browser에서 서버로 최초요청 발생) @SessionScope로 정의된 Bean객체가 주입되며 이후 요청이 발생하여도 Bean객체는 재 주입되지 않는다.
-- Xml 설정.
java 설정과 거의 동일하며 "빈 등록" 및 "컴포넌트스캔" 설정부분만 다르다.
1. root-context.xml 수정 - "빈 수동등록"
* 빈 수동등록 <bean class="빈 경로" scope="session" id="빈 이름"/>
--> id 속성 지정시 @Resource(name="빈 이름") 으로 주입받으며, 객체주입시 Session영역에 자동으로 저장된다.
2. servlet-context.xml 수정 - "컴포넌트스캔: 빈 자동등록"
* 컴포넌트 스캔 경로 등록 - 스캔경로 관하여, @Component설정 빈(Bean) 자동등록
<context:component-scan base-package="컴포넌트 스캔경로" />
* Xml.설정파일에 선언한 빈(Bean) 주입 시도시. scope="session"으로 설정하여도 최초요청 발생시 객체주입이 아닌, 애플리케이션이 구동될 시 빈(Bean) 주입을 시도하여 에러가 발생한다. 문제를 해결하기 위해 @Lazy어노테이션 활용.
@Controller
public class TestSessionBeanScope {
@Autowired
@Lazy
SessionBean1 sessionBean1;
}
'SpringMVC' 카테고리의 다른 글
[SpringMVC] ApplicationScope Bean(2) (0) | 2021.10.16 |
---|---|
[SpringMVC] ApplicationScope(1) (0) | 2021.10.11 |
[SpringMVC] SessionScope(1) (0) | 2021.09.20 |
[SpringMVC] RequestScope Bean(2) (0) | 2021.09.14 |
[SpringMVC] RequestScope(1) (0) | 2021.09.10 |