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;
}
}
package chap02;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration //빈객체를 담는 컨테이너
public class AppContext {
@Bean
public Greeter greeter() { //Greeter 의 객체를 담고 있는 함수
Greeter g = new Greeter();
g.setFormat("%s, 안녕하세요!");
return g;
}
}
@Configuration 애노테이션은 해당 클래스를 스프링 설정 클래스로 지정한다.
스프링이 생성하는 객체를 빈(Bean)객체라고 한다.
@Bean 애노테이션을 메서드에 붙이면 해당 메서드가 생성한 객체를 스프링이 관리하는 빈 객체로 등록한다.
package chap02;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(AppContext.class);
//AppContext에 정의한 @Bean 설정 정보를 읽어와 Greeter 객체를 생성하고 초기화
//~.class : ~의 객체/주소!
// ctx 객체는 Greeter 클래스에 의존한다.
// Greeter 클래스가 없인(주소 없인) ctx는 무의미하기 때문?
Greeter g = ctx.getBean("greeter", Greeter.class);
//getBean 메서드의 첫 번째 파라미터는 @Bean 애노테이션의 메서드 이름인 빈 객체의 이름,
두 번째 파라미터는 검색할 빈 객체의 타입
String msg = g.greet("스프링");
System.out.println(msg);
ctx.close();
}
}
AnnotationConfigApplicationContext 클래스는 자바 설정에서 정보를 읽어와 빈 객체를 생성하고 관리함.
스프링의 핵심 기능은 객체를 생성하고 초기화 하는것이다. 이와 관련된 기능은 AnnotationConfigApplicationContext 라는 인터페이스에 정의되어 있다.
- AnnotationConfigApplicationContext : 자바 애노테이션을 이용한 클래스로부터 객체 설정 정보를 가져온다.
- GenericXmlApplicationContext : xml로부터 객체 설정 정보를 가져온다.
ApplicationContext는 빈 객체의 생성, 초기화, 보관, 제거 등을 관리하고 있어서 ApplicationContext나 BeanFactory 등을 스프링 컨테이너라고 표현한다.
스프링은 한 개의 빈 객체만을 생성하며, 이때 빈 객체는 '싱글톤 범위를 갖는다'고 표현한다.
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)); //true! g1,g2는 같은 객체다.
ctx.close();
}
}