Spring & Springboot/올인원 스프링 프레임워크

학사 관리 시스템 -4

YJ_ma 2023. 9. 14. 00:59

스프링 빈 범위

IoC 컨테이너에 생성된 빈을 getBean()으로 호출하면 항상 동일한 객체가 반환된다.

→ 스프링은 기본적으로 객체 범위를 싱글턴으로 관리하기 때문이다.

싱글턴 (스프링 빈 범위) : 객체를 호출할 때마다 새로 생성하지 않고 기존의 객체를 재활용 하는 것

 

ch04_pjt_02 프로젝트를 생성하고 다음 구조처럼 나타낸다.

1. 메이븐 설정 파일

pom.xml에서 spring-context 모듈과 빌드를 설정한다.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>spring5</groupId>
  <artifactId>ch04_pjt_02</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <!-- spring-context 모듈-->
  <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.9.RELEASE</version>
    </dependency>
  </dependencies>
  
  <!-- 빌드설정-->
  <build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>11</source>
                <target>11</target>
                <encoding>utf-8</encoding>
            </configuration>
        </plugin>
    </plugins>
  </build>
  
</project>

 

2. DependencyBean 클래스

객체가 생성될 때 생성자를 통해서 InjectionBean을 주입받는다.

package ch04_pjt_02.scope;

public class DependencyBean {
	InjectionBean injectionBean;

	public DependencyBean(InjectionBean injectionBean) {
		this.injectionBean = injectionBean;
	}
}

 

3. InjectionBean 클래스

멤버가 없는 객체로 컴파일 단계에서 디폴트 생성자가 추가된다.

package ch04_pjt_02.scope;

public class InjectionBean {

}

 

4. 스프링 설정 파일

applicationContext.xml에서는 InjectionBean 빈을 생성해서 DependencyBean에 생성자를 통해서 객체를 주입한다.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
    https://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="injectionBean" class="ch04_pjt_02.scope.InjectionBean"/>

	<bean id="dependencyBean" class="ch04_pjt_02.scope.DependencyBean">
		<constructor-arg ref="injectionBean"/>
	</bean>
	
</beans>

 

5. MainClass 클래스

main() 메서드에서 IoC 컨테이너를 생성하고 DependencyBean 빈을 가져온다.

이때 dependencyBean_01과 dependencyBean_02로 두 번 가져온다.

package ch04_pjt_02.scope;

import org.springframework.context.support.GenericXmlApplicationContext;

public class MainClass {

	public static void main(String[] args) {

		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationContext.xml");

		DependencyBean dependencyBean_01 = ctx.getBean("dependencyBean", DependencyBean.class);
		DependencyBean dependencyBean_02 = ctx.getBean("dependencyBean", DependencyBean.class);

		if (dependencyBean_01.equals(dependencyBean_02)) {
			System.out.println("dependencyBean_01 == dependencyBean_02");

		} else {
			System.out.println("dependencyBean_01 != dependencyBean_02");

		}

		ctx.close();

	}

}

스프링은 싱글턴이기 때문에 dependencyBean_01과 dependencyBean_02는 동일한 객체를 참조하고 있다.

실행 결과

정리하면 스프링 컨테이너에서 생성된 빈을 getBean() 메서드로 이용해서 가져오면 가져올 때마다 새로운 빈이 생성되는 것이 아닌 동일한 빈이 계속해서 사용된다.

이를 스프링에서 싱글턴이라하고, 기본적으로 모든 빈은 싱글턴 범위를 갖는다.

싱글턴 범위와 반대를 프로토타입 범위라고한다. 다음과 같이 스프링 설정 파일에서 빈을 정의할 때 scope 속성을 명시해준다.

 

applicationContext.xml에서 scope="prototype"을 명시하고, 프로그램을 실행하면 다음과 같이 다른 객체가 생성되는 것을 확인할 수 있다.

<bean id="dependencyBean" class="ch04_pjt_02.scope.DependencyBean" scope="prototype">
    <constructor-arg ref="injectionBean"/>
</bean>

 

 

 

 

 

 

 

 

'Spring & Springboot > 올인원 스프링 프레임워크' 카테고리의 다른 글

스마트폰 연락처 -2  (0) 2023.09.19
스마트폰 연락처 -1  (0) 2023.09.17
학사 관리 시스템 -3  (0) 2023.09.14
학사 관리 시스템 -2  (0) 2023.09.13
학사 관리 시스템 -1  (0) 2023.09.13