AnnotationConfigApplicationContext 주요 메서드 완전 정복
Spring을 공부하면서 자바 기반 설정을 쓸 때 꼭 만나게 되는 클래스가 바로 AnnotationConfigApplicationContext입니다.
이 글에서는 이 클래스의 주요 메서드를 하나씩 살펴보면서, 직접 써볼 수 있는 예제 코드와 함께 이해를 돕겠습니다.
기본 개념 다시 한 번
AnnotationConfigApplicationContext는 Java 코드 기반 설정을 읽어서 Spring 컨테이너(ApplicationContext)를 구성하는 클래스입니다. 즉, 설정 클래스만 있으면 XML 없이도 Bean 등록, 컴포넌트 스캔, 의존성 주입이 다 가능합니다.
1. register(Class<?>... annotatedClasses)
하나 이상의 자바 설정 클래스(@Configuration)를 직접 등록할 때 사용합니다.
@Configuration
public class AppConfig {
@Bean
public HelloService helloService() {
return new HelloService();
}
}
public class HelloService {
public void sayHello() {
System.out.println("안녕하세요!");
}
}
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(AppConfig.class); // 설정 클래스 등록
context.refresh(); // 컨텍스트 초기화
HelloService hello = context.getBean(HelloService.class);
hello.sayHello();
context.close();
}
}
2. scan(String... basePackages)
설정 클래스를 따로 만들지 않고, 패키지 경로만 지정해서 컴포넌트(@Component, @Service 등)를 스캔할 수 있습니다.
@Component
public class GreetingService {
public void greet() {
System.out.println("환영합니다!");
}
}
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.example"); // 이 패키지에서 컴포넌트 스캔
context.refresh();
GreetingService gs = context.getBean(GreetingService.class);
gs.greet();
context.close();
}
}
GreetingService 클래스가 com.example 패키지에 있어야 스캔됩니다.
3. refresh()
register()나 scan()을 호출한 후 실제로 컨텍스트를 초기화하는 메서드입니다.
이 메서드를 호출하지 않으면 빈 등록이 완료되지 않습니다.
- register() 또는 scan()만 호출하고 refresh()를 안 하면 예외가 발생합니다.
- Spring Boot에서는 자동 호출되지만, 순수 Spring에서는 명시적으로 호출해야 합니다.
4. getBean(Class<T> requiredType) / getBean(String name)
컨텍스트에 등록된 Bean을 꺼내는 메서드입니다.
HelloService service1 = context.getBean(HelloService.class);
HelloService service2 = (HelloService) context.getBean("helloService");
@Bean으로 등록된 메서드명이 빈 이름이 됩니다.
5. close()
컨텍스트를 종료하고 내부 자원을 해제합니다.
빈에 @PreDestroy 메서드가 있다면 여기서 호출됩니다.
@Component
public class CleanupService {
@PreDestroy
public void shutdown() {
System.out.println("리소스 정리 중...");
}
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.example");
context.refresh();
context.close(); // 종료되며 @PreDestroy 실행
}
사실 가장 많이 쓰이는 패턴은 아래 한 줄짜리 생성자입니다.
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
이렇게 하면 register() + refresh()를 내부에서 자동으로 처리해줍니다.
정리
메서드 | 설명 |
register() | 자바 설정 클래스 등록 |
scan() | 패키지 기준 컴포넌트 스캔 |
refresh() | 등록된 설정을 기반으로 컨텍스트 초기화 |
getBean() | 등록된 빈 꺼내기 |
close() | 컨텍스트 종료 및 리소스 정리 |
Spring을 공부하는 초보자라면 XML보다 AnnotationConfigApplicationContext를 활용한 자바 설정 방식이 더 쉽고 명확하게 느껴질 수 있습니다.
위 메서드들만 익혀도 작은 프로젝트는 충분히 구성해볼 수 있습니다.