티스토리 뷰

스프링은 객체를 초기화하고 관리해준다. 

 

Greeter.java

package chap02;

public class Greeter 
{
	private String format;
	
	public String greet(String guest) 
	{
		return String.format(format, guest);
	}
	
	public void setFormat(String format) 
	{
		this.format = format;
	}
}

 

AppContext.java

package chap02; 

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration // Spring 설정 클래스 지정  
public class AppContext 
{
	@Bean // 이 메소드가 생성한 객체를 스프링이 관리하는 '빈 객체'로 등록 
	public Greeter greeter() 
	{
		Greeter g = new Greeter();
		g.setFormat("%s, 안녕하세요!");
		return g;
	}
	
}

 

@Configuration 애노테이션은 해당 클래스가 스프링 설정 클래스임을 지정한다. 

@Bean 애노테이션은 해당 메소드가 생성한 객체를 스프링이 관리하는 '빈(Bean) 객체'로 등록한다. 

 

Bean 객체란 스프링이 생성하고 관리하는 객체이다.

 

 

Main.java

package chap02;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main 
{
	
	public static void main(String[] args) 
	{
		AnnotationConfigApplicationContext ctx = 
				new AnnotationConfigApplicationContext(AppContext.class);
		
		// getBean(빈 객체 이름, 빈 객체 타입) 
		// greeter 메서드가 생성한 Greeter 객체 리턴 
		Greeter g = ctx.getBean("greeter", Greeter.class);
		String msg = g.greet("스프링");
		System.out.println(msg);
		ctx.close();
	}
}

 

AnnotationConfigApplicationContext 객체가 AppContext 클래스에서 정의한 @Bean 설정 정보를 읽어와 Greeter 객체를 생성하

고 초기화한다.

이후 getBean() 메서드로 해당하는 객체를 가져온다.

 

 

싱글톤 객체

스프링은 한 개의 @Bean 애노테이션에 대하여 한 개의 빈 객체 만을 생성한다.

예를들어 다음과 같이하면

Greeter g1 = ctx.getBean("greeter", Greeter.class);

Greeter g2 = ctx.getBean("greeter", Greeter.class);

 

g1과 g2는 정확히 같은 객체이다. 

 

아마 싱글톤 디자인 패턴에 대한 내용같은데 자세한 내용은 뒤에 나온다고 한다.

 

출처: 스프링5 프로그래밍 입문 (최범균 저)

'Web' 카테고리의 다른 글

Ch03. DI 방식, Singleton  (0) 2022.06.23
Ch03. Spring Container, ApplicationContext 설정 파일  (0) 2022.06.01
Ch03. Dependency Injection (의존 주입)  (0) 2022.05.30
Ch02. 스프링 시작하기, Maven  (0) 2022.05.30
Spring 시작  (0) 2022.05.28
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
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
글 보관함