신규 블로그를 만들었습니다!

2020년 이후부터는 아래 블로그에서 활동합니다.

댓글로 질문 주셔도 확인하기 어려울 수 있습니다.

>> https://bluemiv.tistory.com/

스프링의 범위 Scope

스프링은 default scope 값으로 singleton(싱글톤)을 가지고 있다.

 

그래 따로 설정하지 않아도, 싱글톤으로 되어 있기때문에 생략이 가능하다.

싱글톤 말고도 session, request, prototype와 같은 값들로 설정이 가능하다.

 

applicationCTX.xml

 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
 
    <context:annotation-config></context:annotation-config>
 
    <bean id="student" class="com.spring.ex.Student" scope="singleton">
        <property name="name">
            <value>hongku</value>
        </property>
        <property name="age">
            <value>26</value>
        </property>
    </bean>
 
</beans>

그래도 scope의 값으로 singleton으로 설정해보자

 

Main.java

package com.spring.ex;
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class Main {
 
    public static void main(String[] args) {
            
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
        ctx.load("classpath:applicationCTX.xml");
        ctx.refresh();
        
        // student 생성
        Student student = ctx.getBean("student", Student.class);
        System.out.println(student.toString());
        
        // student2 생성
        Student student2 = ctx.getBean("student", Student.class);
        // 값을 넣어줌
        student2.setName("hong");
        student2.setAge(100);
        System.out.println(student2.toString());
        
        // 하지만, student와 student2는 같다
        if(student.equals(student2)) {
            System.out.println("student == student2");
        }else {
            System.out.println("student != student2");
        }
        // student 값도 한번 출력해보자
        System.out.println(student.toString());
    }
}​

 

분명 보기에는 student 객체와 student2 객체는 달라보인다.

그래서, student2 의 값을 변경해도 student에는 영향을 줄거 같아 보이지 않는다.

 

하지만, 스프링 scope를 싱글톤으로 했기 때문에, 둘은 같은 객체를 바라보고 있다는것을 확인 할 수 있다.

 

if(student.equals(student2)) {
    System.out.println("student == student2");
}else {
    System.out.println("student != student2");
}
​

 

위 if문의 결과는 어떻게 나올까?

답은 student == student2이다.

 

 

위에서 student2의 값을 setter 메소드를 이용해서 설정을 했다

(name = hong, age = 100)

 

이때, student 의 값을 출력해보자.

그냥 보기에는 name = hongku, age = 26 이 나와야 할 것 같다...

 

System.out.println(student.toString());

결과는 student2의 값이 나온다. (name = hong, age = 100)

 

 

즉, student와 student2는 같은 객체를 바라보고 있다는것을 알 수 있다.

 

※ 이 글은 Seoul Wiz - '실전 Spring 강좌'를 요약하여 작성하였습니다.

>> 유튜브 - SeoulWiz 

 
 

 

 

  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기