본문 바로가기
JAVA/JAVA 기본

Bean Scope & Singleton

by F.E.D 2018. 4. 12.

Bean Scope

Bean Scope는 객체가 유효한 범위 아래 5가지의 scope가 있다.

 Scope

 Detail 

 singleton

 하나의 Bean 정의에 대해서 Spring IoC Container 내에 단 하나의 객체만 존재한다.

 prototype

 하나의 Bean 정의에 대해서 빈을 사용할 때 마다 객체를 생성 한다.

 request

 HTTP 요청마다 객체를 생성 한다. 즉 HTTP request의 생명주기 안에 단 하나의 객체만 존재한다

 session HTTP 세션마다 객체를 생성 한다. 즉 HTTP Session의 생명주기 안에 단 하나의 객체만 존재한다
 global-session 글로벌 HTTP 세션 안에 단 하나의 객체만 존재한다


Bean이 singleton인 경우, 단지 하나의 공유 객체만 관리된다.

Singleton scope는 Spring의 기본 scope이다.

Container 당 하나의 객체라는 의미에서 singleton 이다.

JVM의 classloader당 하나의 객체라는 의미에 GoF의 Singleton과는 다르다.



Bean Singleton Scope

1
2
3
4
5
<bean id="beanScope" class="com.bean.beanScopeImpl"/>
 
<bean id="beanScope" class="com.bean.beanScopeImpl" scope="singleton"/>
 
<bean id="beanScope" class="com.bean.beanScopeImpl" singleton="true"/>
cs



Singleton

프로그래밍 세계에 OOP 의 개념이 생기면서 객체 자체에 대한 많은 연구와 패턴(pattern)들이 생겨났다. 


singleton pattern은 인스턴스가 사용될 때에 똑같은 인스턴스를 만들어 내는 것이 아니라, 


동일 인스턴스를 사용하게끔 하는 것이 기본 전략이다. 


프로그램상에서 동일한 커넥션 객체를 만든다던지, 하나만 사용되야하는 객체를 만들때 매우 유용하다. 


singleton pattern은 4대 디자인 패턴에 들어갈 정도로 흔히 쓰이는 패턴이다. 



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class YmInitial {
    // private static 로 선언.
    private static YmInitial instance = new YmInitial();
    // 생성자
    private YmInitial () {
        System.out.println"call YmInitial." );
    }
    // 조회 method
    public static YmInitial getInstance () {
        return instance;
    }
    
    public void print () {
        System.out.println("print() method in YmInitial instance.");
        System.out.println("instance hashCode > " + instance.hashCode());
    }
}
 
cs



가장 기본적인 singleton pattern으로써 전역 변수로 instance를 만들고 private static을 사용한다.


static이 붙은 클래스변수는 인스턴스화에 상관없이 사용이 가능하게 된다. 


하지만 private 접근제어자로 YmInitial로의 접근은 불가하다.


이런 상태에서 생성자를 private로 명시한다. 


생성자를 private로 붙이게되면, new 키워드를 사용할 수 없게된다. 


즉, 다른 클래스에서 YmInitial instance = new YmInitial(); 


이런 방법을 통한 인스턴스 생성은 불가능해진다. 


결국 외부 클래스가 YmInitial 클래스의 인스턴스를 가질 수 있는 방법은 


getInstance() method를 사용하는 방법외엔 없다.





출처 : 

http://wiki.gurubee.net/pages/viewpage.action?pageId=26740787

https://blog.seotory.com/post/2016/03/java-singleton-pattern




'JAVA > JAVA 기본' 카테고리의 다른 글

Java에서 HashMap 사용하기  (0) 2018.05.24
인터셉터란? JSP Filter와의 비교, url-pattern  (0) 2018.05.14
[자료구조] 큐(Queue)  (0) 2018.04.15
REST의 기본  (2) 2018.04.15
IoC(Inversion of Control) 제어의 역전 현상  (0) 2018.04.12

댓글