Spring의 애플리케이션 컨텍스트 기능과 활용

ApplicationContext는 스프링 프레임워크의 핵심 인터페이스로, 의존성 주입 및 컴포넌트 관리를 중심으로 동작하는 컨테이너 역할을 합니다. 이는 BeanFactory보다 확장된 기능을 제공하며, 빈의 생명주기 제어, 국제화 처리, 이벤트 전달, 리소스 접근 등 다양한 기업급 서비스를 통합적으로 지원합니다.

주요 기능

  • 빈 생성 및 관리: 애플리케이션 내 모든 빈 인스턴스를 생성하고 유지 관리합니다.
  • 의존성 주입: 빈 간의 종속성을 자동으로 해결하여 결합도를 낮춥니다.
  • 국제화 지원: MessageSource를 통해 다국어 메시지 제공 가능.
  • 이벤트 시스템: 발행-구독 패턴을 기반으로 한 이벤트 전달 메커니즘 제공.
  • 생명주기 콜백: 초기화 및 종료 메서드를 정의해 빈의 준비와 정리 작업을 지원.
  • 자원 접근: 파일 시스템, 클래스패스 등 다양한 리소스에 대한 편리한 접근 제공.

주요 구현 클래스

  • ClassPathXmlApplicationContext: 클래스패스 상의 XML 설정 파일을 기반으로 컨텍스트 로드.
  • FileSystemXmlApplicationContext: 파일 시스템 경로에 위치한 XML 파일을 사용.
  • AnnotationConfigApplicationContext: 자바 기반 설정 클래스를 이용해 컨텍스트 구성 (대표적인 @Configuration 방식).

사용 예제

다음은 AnnotationConfigApplicationContext를 사용해 빈을 등록하고 활용하는 간단한 예제입니다.

1. Maven 의존성 설정

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.20</version>
</dependency>

2. 빈 정의

public class GreetingService {
    public void greet() {
        System.out.println("안녕하세요, 스프링!");
    }
}

3. 설정 클래스 작성

@Configuration
public class AppConfiguration {
    @Bean
    public GreetingService greetingService() {
        return new GreetingService();
    }
}

4. 컨텍스트 사용

public class ApplicationRunner {
    public static void main(String[] args) {
        ApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfiguration.class);
        
        GreetingService service = appContext.getBean(GreetingService.class);
        service.greet();
    }
}

이벤트 기능 활용

ApplicationContext는 사용자 정의 이벤트를 발행하고 수신할 수 있는 기능을 제공합니다.

1. 이벤트 클래스 정의

import org.springframework.context.ApplicationEvent;

public class CustomNotificationEvent extends ApplicationEvent {
    private final String message;

    public CustomNotificationEvent(Object source, String message) {
        super(source);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

2. 이벤트 리스너 구현

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class NotificationListener implements ApplicationListener<CustomNotificationEvent> {
    @Override
    public void onApplicationEvent(CustomNotificationEvent event) {
        System.out.println("수신된 알림: " + event.getMessage());
    }
}

3. 이벤트 발행

public class EventPublisher {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfiguration.class);

        GreetingService service = context.getBean(GreetingService.class);
        service.greet();

        // 사용자 정의 이벤트 발행
        context.publishEvent(new CustomNotificationEvent(context, "시스템 시작 완료!"));
    }
}

출력 결과

안녕하세요, 스프링!
수신된 알림: 시스템 시작 완료!

정리

  • ApplicationContext는 스프링의 중심 인터페이스로, 빈 관리부터 이벤트 처리까지 포괄적인 기능을 제공합니다.
  • 설정 방식에 따라 XML, Java Config 기반의 다양한 구현 클래스가 존재합니다.
  • 이벤트 시스템을 활용하면 모듈 간 느슨한 결합을 유지하면서 비동기적 통신이 가능합니다.
  • 스프링 기반의 확장성과 유연성을 갖춘 애플리케이션 개발에 필수적인 요소입니다.

태그: Spring Framework ApplicationContext Dependency Injection event handling Java Configuration

7월 9일 02:06에 게시됨