2. 스프링 시작하기 #3 싱글톤(Singleton) 객체
2021. 7. 1. 22:25ㆍJAVA/Spring
2.1 싱글톤(Singleton) 객체
package chap02;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main2 {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(AppContext.class);
Greeter g1 = ctx.getBean("greeter", Greeter.class);
Greeter g2 = ctx.getBean("greeter", Greeter.class);
System.out.println("(g1 == g2) = " + (g1 == g2));
ctx.close();
}
}
Result
(g1==g2) = true
- "greeter"인 빈 객체를 구해서 g1과 g2 변수에 할당한다.
- g1과 g2가 같은 객체인지 여부를 콘솔에 출력한다.
- 결과는 True로 출력된다.
(g1==g2)의 결과가 true라는 것은 g1과 g2가 같은 객체라는 것을 의미한다. 즉, 위의 코드에서 getBean() 메서드는 같은 객체를 리턴하는 것이다.
별도 설정을 하지 않을 경우 스프링은 한 개의 빈 객체만을 생성하며, 이때 빈 객체는 '싱글톤(singleton) 범위를 갖는다'고 표현한다. 싱글톤은 단일 객체를 의미하는 단어로서 스프링은 기본적으로 한 갱의 @Bean 애노테이션에 대해 한 개의 빈 객체를 생성한다.
싱글톤 범위를 갖지 않는 객체를 2개 갖기 위해서는 아래와 같이 "greeter"에 해당하는 객체 한개와 "greeter1"에 해당하는 객체 한개, 이렇게 2개의 빈 객체를 생성하면 된다.
@Bean
public Greeter greeter() {
Greeter g = new Greeter();
g.setFormat("%s, 안녕하세요!");
return g;
}
@Bean
public Greeter greeter1() {
Greeter g = new Greeter();
g.setFormat("%s, 안녕하세요!");
return g;
}
싱글톤 범위 외에 프로토타입 범위도 존재한다.
'JAVA > Spring' 카테고리의 다른 글
3. 스프링 DI(Dependency Injection) #2 객체 조립 (0) | 2021.07.02 |
---|---|
3. 스프링 DI(Dependency Injection) #1 객체 의존과 의존 주입(DI) (0) | 2021.07.02 |
2. 스프링 시작하기 #2 그레이들 프로젝트 생성 (0) | 2021.07.01 |
2. 스프링 시작하기 #1 메이븐 프로젝트 생성 (0) | 2021.07.01 |
1. 스프링5 소개 및 개발 환경 구축 (0) | 2021.06.30 |