Spring 에서 Bean 의 역할 영역
본문 은 두 부분 으로 나 눌 것 이다.각 부분 마다 bean 역할 영역 을 설명 합 니 다.그래서 첫 번 째 로 request 요청 역할 영역 을 검토 하 겠 습 니 다.두 번 째 설명 은 session 과 전역 session (스프링 5 문서 에서 사 라 졌 습 니 다) 의 역할 영역 입 니 다.모든 부분 은 이론 과 실천 으로 구 성 될 것 이다.주의해 야 할 것 은 이러한 개념 은 웹 스프링 응용 프로그램의 상하 문 에서 만 유효 하 다 는 것 이다.
Spring 에서 request 요청 역할 영역 은 무엇 입 니까?
요청 마다 이 역할 영역 을 가 진 Bean 주 해 를 초기 화 합 니 다.이것 은 원형 작용 역 의 묘사 처럼 들 리 지만, 그것들 은 약간의 차이 가 있다.첫 번 째 차 이 는 원형 역할 영역 이 Spring 의 문맥 에서 사용 할 수 있다 는 것 이다.요청 도 메 인 은 웹 프로그램 에 만 적 용 됩 니 다.두 번 째 는 원형 bean 이 수요 에 따라 초기 화 되 고 요청 bean 은 모든 요청 에 따라 구 축 됩 니 다.필요 한 것 은 request 역할 영역 bean 은 그 역할 영역 에 있 고 하나의 인 스 턴 스 만 있 습 니 다.하나 이상 의 원형 역할 영역 bean 인 스 턴 스 를 가 질 수 있 습 니 다.
다음 코드 에서 요청 역할 영역 bean 의 예제 를 볼 수 있 습 니 다.
주해 구동 구성 요소 나 자바 Config 를 사용 할 때 @ RequestScope 주 해 는 하나의 구성 요 소 를 request 역할 영역 에 할당 하 는 데 사용 할 수 있 습 니 다.
@RequestScope
@Component
public class ShoppingCartRequest {
// ...
}
// request bean
// injection sample
@Controller
public class TestController {
@Autowired
private ShoppingCartRequest shoppingCartRequest;
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test(HttpServletRequest request) {
LOGGER.debug("shoppingCartRequest is :"+shoppingCartRequest);
// ...
}
}
빈 > 존재 하 는 탭 을 정의 하 는 데 주의 하 십시오.이것 은 대리 대상 을 사용 하 는 것 을 대표 한다.그래서 실제로 TestController 는 대리 대상 의 인용 을 가지 고 있다.우리 의 모든 호출 대상 은 진정한 ShoppingCartRequest 대상 에 게 전 달 됩 니 다.
때때로 우 리 는 Dispatcher Servlet 의 다른 servlet 를 사용 하여 요청 을 처리 해 야 한다.이러한 상황 에서 우 리 는 Spring 의 모든 요청 을 사용 할 수 있 도록 확보 해 야 한다 (그렇지 않 으 면 아래 와 유사 한 이상 을 던 질 수 있다).이 를 위해 서 는 웹 xml 에서 모니터 를 정의 해 야 합 니 다.
org.springframework.web.context.request.RequestContextListener
URL 을 호출 / 테스트 한 후 로그 에서 다음 과 같은 정 보 를 발견 할 수 있 을 것 입 니 다.
shoppingCartRequest is :com.waitingforcode.scope.ShoppingCartRequest@2586b11c
shoppingCartRequest is :com.waitingforcode.scope.ShoppingCartRequest@3bd5b945
만약 우리 가 하나의 bean 에서 request 역할 도 메 인 을 사용 하려 고 시도 한다 면, 응용 프로그램 컨 텍스트 로 딩 단계 에서 BeanCreation Exception 을 던 질 것 입 니 다.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.waitingforcode.scope.ShoppingCartRequest com.waitingforcode.controller.TestController.shoppingCartRequest; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shoppingCartRequest': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:381)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:293)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.waitingforcode.scope.ShoppingCartRequest com.waitingforcode.controller.TestController.shoppingCartRequest; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shoppingCartRequest': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 21 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shoppingCartRequest': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:353)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:957)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 23 more
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
at org.springframework.web.context.request.AbstractRequestAttributesScope.get(AbstractRequestAttributesScope.java:41)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:338)
... 28 more
Spring 의 Session 역할 영역 은 무엇 입 니까?
Session 역할 영역의 bean 과 request 역할 영역의 bean 은 크게 다 르 지 않다.그것들 도 순수한 웹 응용 프로그램의 상하 문과 관련 이 있다.Session 역할 영역 으로 주 해 된 Bean 은 모든 사용자 의 세 션 을 한 번 만 듭 니 다.그들 은 대화 가 끝 날 때 파괴 되 어 소각 되 었 다.Session 역할 영역 에서 제 한 된 Bean 은 웹 을 위 한 단일 예 로 여 겨 질 수 있 습 니 다. 주어진 환경 (사용자 세 션) 에 하나의 인 스 턴 스 만 존재 하기 때 문 입 니 다.그러나 웹 프로그램 컨 텍스트 에서 사용 할 수 없다 는 것 을 기억 하 십시오.Session 역할 영역 bean 이 Spring 에서 의 동작 을 알 고 싶 습 니 다. 설정 파일 에서 bean 을 정의 해 야 합 니 다.
@ Autowired 주 해 를 통 해 이 bean 을 찾 는 방식 은 request 역할 영역의 bean 과 같 습 니 다.다음 결 과 를 볼 수 있 습 니 다:
shoppingCartSession is :com.waitingforcode.scope.ShoppingCartSession@3876e5d
shoppingCartSession is :com.waitingforcode.scope.ShoppingCartSession@3876e5d
shoppingCartSession is :com.waitingforcode.scope.ShoppingCartSession@3876e5d
shoppingCartSession is :com.waitingforcode.scope.ShoppingCartSession@3876e5d
shoppingCartSession is :com.waitingforcode.scope.ShoppingCartSession@3876e5d
shoppingCartSession is :com.waitingforcode.scope.ShoppingCartSession@2f87fafc
앞의 5 개의 인쇄 출력 은 같은 대상 을 대표 하 는 것 을 볼 수 있다.마지막 하 나 는 다르다.이것 은 무슨 뜻 입 니까?쉽게 말 하면 이것 은 새로운 사용자 가 자동 으로 주입 하 는 Session 역할 도 메 인 을 사용 하여 이 페이지 를 방문 하 는 것 을 의미한다.우 리 는 두 브 라 우 저의 테스트 페이지 (/ test) 를 열 어 그것 을 관찰 할 수 있다.각각 새로운 세 션 세 션 을 초기 화 합 니 다. 따라서 새로운 ShoppingCartSession bean 인 스 턴 스 를 만 듭 니 다.
전역 세 션 역할 영역 (Global session scope) 은 4.3x 의 범주 에 속 합 니 다. Spring 5 는 이미 없습니다. Spring 5 문 서 는 4 의 존재 로 인해 두 마디 하 는 것 을 제거 하고 portlet 응용 프로그램 에 보관 합 니 다.어리둥절 한 얼굴 인지, so, portlet 이 무엇 인지 설명해 주세요.Portlet 은 의미 코드 (예: HTML) 세 션 을 만 들 수 있 는 작은 자바 웹 플러그 인 입 니 다.portlet 용 기 를 기반 으로 servlet 처럼 HTTP 요청 을 처리 할 수 있 습 니 다.그러나 servlet 과 달리 portlet 마다 세 션 이 다르다.이런 상황 에서 스프링 은 글로벌 세 션 이라는 역할 영역 을 제공 했다.이 를 통 해 하나의 bean 은 응용 프로그램의 여러 portlet 를 통 해 공유 할 수 있 습 니 다.
이로써 우 리 는 요청 과 세 션 을 위 한 역할 영역 을 설명 했다.첫 번 째 역할 은 모든 request 요청 에 새로운 bean 을 만 드 는 것 입 니 다.두 번 째 는 세 션 세 션 이 시 작 될 때 bean 을 초기 화 합 니 다.
Spring 에서 Bean 의 역할 영역
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.