본문 바로가기
프로그래밍/Spring

Spring / 스프링 빈의 범위(Bean Scope)

by 소소로드 2018. 4. 7.

[스프링 빈의 범위(Bean Scope)]

: 빈의 범위는 해당 객체가 어디까지 영향을 미치는 가를 결정하는 부분이라고 한다.

  별도로 scope를 지정하지 않으면 디폴트값은 singleton이며

  종류는 singletone, prototype, request, session, global session가 있는데 singletone만 다뤘다.





Student.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class Student {
    
    private String name;
    private int age;
    private ArrayList<String> hobbies;
    private double height;
    private double weight;
    
    public Student(String name, int age, ArrayList<String> hobbies) {
        this.name = name;
        this.age = age;
        this.hobbies = hobbies;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public ArrayList<String> getHobbies() {
        return hobbies;
    }
 
    public void setHobbies(ArrayList<String> hobbies) {
        this.hobbies = hobbies;
    }
 
    public double getHeight() {
        return height;
    }
 
    public void setHeight(double height) {
        this.height = height;
    }
 
    public double getWeight() {
        return weight;
    }
 
    public void setWeight(double weight) {
        this.weight = weight;
    }
 
}
cs





ctx_BeanScope.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<bean id="student" class="com.yul.ex06_example.Student" scope="singleton">
    <constructor-arg value="yul"/>
    <constructor-arg value="100"/>
    <constructor-arg>
        <list>
            <value>노래부르기</value>
            <value>코딩하기</value>
        </list>
    </constructor-arg>
    <property name="height"  value="172"/>
    <property name="weight" value="56"/>
</bean>
 
</beans>
cs

*

scope가 singleton으로 설정되었다.

사실 이렇게 적어주지 않아도 default값이 singleton이라고 위에서 밝혀두었다.

singleton의 정확한 의미는 "하나의 Bean정의에서 스프링컨테이너 내에 단 하나의 객체만 존재"한다는 뜻이다.

이게 무엇을 의미하는지 생각해보고 MainClass에서 살펴보자.




MainClass.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class MainClass {
 
    public static void main(String[] args) {
        
        AbstractApplicationContext ctx 
            = new GenericXmlApplicationContext("classpath:ctx_BeanScope.xml");
    
        Student student1 = ctx.getBean("student", Student.class);
        System.out.println("이름 : " + student1.getName());
        System.out.println("나이 : " + student1.getAge());
        System.out.println("---------------------------------------------");
        
        Student student2 = ctx.getBean("student", Student.class);
        student2.setName("홍길동");
        student2.setAge(24);
        System.out.println("이름 : " + student2.getName());
        System.out.println("나이 : " + student2.getAge());
        System.out.println("---------------------------------------------");
        
        if(student1.equals(student2)) {
            System.out.println("student1과 student2는 같다");
        } else {
            System.out.println("student1과 student2는 다르다"); // 같다
        }
        // System.out.println(student1.equals(student2));
    }
 
}
cs

*

빈의 범위가 singletone으로 설정된 xml파일은 MainClass에서 어떻게 구현되는가? 가 생각해야 할 부분이다.


student1과 student2는 다른 값을 나타내므로 마치 같은 객체처럼 보인다.

하지만 유심히 보면 student1과 student2는 모두 "student"를 getBean하였다.

xml파일을 보면 yul학생과 관련된 딱 하나의 객체만 만든 것을 볼 수 있다.


결과적으로, student1은 xml의 yul학생을 보여줄 것이고

student2는 setName, setAge를 통해 새로 세팅한 홍길동 학생의 내용을 보여줄 것이다.

두 개는 모두 같은 객체에서 왔으니 if문은 같다라는 결과가 출력된다.


*

singletone이 스프링 컨테이너에서 단 하나의 객체만 존재한다는 말처럼

xml에서 하나만 생성했고, MainClass에서 하나의 객체를 통해 값을 변경하는 부분을 보여준다.