Spring 프로젝트에서 bean 설정 시 scope는?
2020. 9. 13. 22:24ㆍ카테고리 없음
scope 영역에서 prototype 과 singleton 의 차이는?
'singleton’ bean은 Spring 컨테이너에서 한 번 생성된다. 생성된 하나의 인스턴스는 single beans cache에 저장되고, 해당 bean에 대한 요청과 참조가 있으면 캐시된 객체를 반환한다. 즉, 하나만 생성되기 때문에 동일한 것을 참조한다.
기본적으로 모든 bean은 scope가 명시적으로 지정되지 않으면 singleton이다.
‘prototype’ bean은 모든 요청에서 새로운 객체를 생성하는 것을 의미한다.
즉, prototype bean은 의존성 관계의 bean에 주입 될 때 새로운 객체가 생성되어 주입된다.
정상적인 방식으로 gc에 의해 bean이 제거된다.
Attribute : scope
The scope of this bean: typically "singleton" (one shared instance, which will be returned by all calls to getBean with the given id), or "prototype" (independent instance resulting from each call to getBean). By default, a bean will be a singleton, unless the bean has a parent bean definition in which case it will inherit the parent's scope. Singletons are most commonly used, and are ideal for multi-threaded service objects. Further scopes, such as "request" or "session", might be supported by extended bean factories (e.g. in a web environment). Inner bean definitions inherit the scope of their containing bean definition, unless explicitly specified: The inner bean will be a singleton if the containing bean is a singleton, and a prototype if the containing bean is a prototype, etc.
scope 속성
싱글톤: 하나의 공유되는 객체(인스턴스)로서, bean id로 getBean 요청이 있을 때 리턴된다.
프로토타입: 독립적인 객체로서, 각각의 getBean 요청에 대한 결과로 생성된다.
기본적으로(디폴트 값), 하나의 bean은 싱글톤이다. 그러나 부모 bean을 가지고 있으면, 부모의 scope를 상속한다. 싱글톤은 가장 보편적으로 쓰이고, 멀티스레드 서비스 객체에게 가장 이상적이다. 더 나아가, request나 session같은 scope는 웹 환경과 같은 확장된 빈 팩토리에서 지원될 수 있다.(해석했는데 뭔말인지 모름..)
명시적으로 정의하지 않을 경우, inner bean의 scope 정의는 inner bean을 포함하는 bean의 정의를 상속한다. 그 말인즉슨, 포함하는 bean이 싱글톤이면 inner bean도 싱글톤이고, 포함하는 bean이 프로토타입이면, inner bean도 프로토타입이라는 것이다.
** xml 파일에서 bean 설정할 때, scope에 마우스를 올리면 나오는 설명을 번역해봤습니다.