신규 블로그를 만들었습니다!
스프링의 범위 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 강좌'를 요약하여 작성하였습니다.
'WEB > SpringMVC' 카테고리의 다른 글
SpringMVC :: 외부에 있는 파일을 이용해서 빈과 설정값을 set하는 방법 (1126) | 2018.03.11 |
---|---|
SpringMVC :: 스프링 실행 오류 (exit code=13) (589) | 2018.03.11 |
SpringMVC :: 스프링 컨테이너의 생명주기, 빈의 생명주기 (Life cycle), InitialzingBean, DisposableBean, @PreDestroy, @PostConstruct (1119) | 2018.03.10 |
SpringMVC :: java 파일을 이용해서 Bean(빈) 생성하기 (152) | 2018.03.10 |
SpringMVC :: 스프링 property 설정 하는 방법 #3 (0) | 2018.01.11 |
최근댓글