ApplicationContext & ClassPathXmlApplicationContext

정주영·2024년 12월 18일

자바_스프링

목록 보기
2/2

출처 : https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/overview.html

Springframework 에서 가장 핵심적인 요소는 CoreContainer 이다. 그 중에서도
ApplicationContext, ClassPathXmlApplicationContext 를 자세히 알아보자.

ApplicationContext

Spring의 컨테이너 역할: Spring의 IoC(Inversion of Control) 컨테이너 중 하나입니다.
설정 파일(XML, Java Config 등)이나 어노테이션 기반의 설정을 기반으로 빈(Bean) 객체를 관리합니다. Bean의 생성, 의존성 주입, 라이프사이클 관리 등을 책임집니다.

ApplicationContext의 주요 특징

  • Bean Factory 기능

  • 빈 객체 생성 및 관리, 빈 간 의존성 주입(DI)을 자동으로 처리합니다.

  • AOP(Aspect-Oriented Programming) 지원

  • 트랜잭션 관리나 로깅과 같은 공통 기능 구현에 AOP를 활용합니다.
    이벤트 리스너(Event Listeners)

  • Spring 컨테이너가 시작되거나 종료될 때 이벤트를 발생시키고 리스너가 이를 감지합니다.

Spring 컨테이너의 종류

ApplicationContext의 다양한 구현 클래스
Spring Framework에서는 여러 ApplicationContext 구현체가 존재합니다.

  • ClassPathXmlApplicationContext 클래스 경로(Classpath)에서 설정 파일(XML)을 로드합니다.
  • FileSystemXmlApplicationContext 파일 시스템 경로에서 설정 파일을 로드합니다.
  • AnnotationConfigApplicationContext Java Configuration 기반 설정 파일을 로드합니다.
  • WebApplicationContext 웹 애플리케이션 전용 컨테이너입니다. (Spring MVC 컨트롤러 관리)

이번장에서는 ClassPathXmlApplicationContext만 다룹니다.

ClassPathXmlApplicationContext

ClassPathXmlApplicationContext는 스프링 프레임워크에서 제공하는 ApplicationContext 구현체 중 하나로, 주로 XML 파일을 통해 빈(bean) 정의를 로드하고 관리하기 위해 사용됩니다. 이는 클래스패스(classpath)에서 XML 파일을 읽어 애플리케이션 컨텍스트를 구성합니다

ClassPathXmlApplicationContext의 주요 특징

  • 클래스패스 기반

  • XML 파일은 클래스패스 경로에서 검색됩니다.
    따라서, XML 파일은 클래스패스 디렉토리 내에 있어야 합니다.
    BeanFactory의 확장

  • BeanFactory를 확장한 ApplicationContext 구현체로, 빈의 생명 주기 관리 외에 다양한 기능을 제공합니다.
    국제화(i18n), 이벤트 처리, AOP 통합, 환경 추상화 등을 포함.
    XML 파일 지원

  • XML 파일에서 빈 정의를 읽고 이를 기반으로 빈을 생성하고 의존성을 주입합니다.
    부모-자식 컨텍스트 지원

  • 부모 컨텍스트를 지정하면, 부모 컨텍스트에서 정의된 빈을 자식 컨텍스트에서 사용할 수 있습니다.

문서를 참고해보니 해당 클래스의 메소드 중
ClassPathXmlApplicationContext(String[] paths, Class<?> clazz)
ClassPathXmlApplicationContext(String[] paths, Class<?> clazz, ApplicationContext parent)
두 개가 문서상의 설명만으로는 잘 이해가 되지 않는다. 코드를 보면서 함께 보자.

ClassPathXmlApplicationContext(String[] paths, Class<?> clazz)

  • 이 생성자는 부모 컨텍스트가 없으며, 지정된 XML 파일에서 빈을 로드합니다.
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        // XML 설정 파일에서 컨텍스트를 생성
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}, Main.class);

        // 빈 가져오기
        MyBean myBean = (MyBean) context.getBean("myBean");
        myBean.sayHello();
    }
}

java 파일

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="myBean" class="com.example.MyBean"/>
</beans>

설정 파일 applicationContext.xml

package com.example;

public class MyBean {
    public void sayHello() {
        System.out.println("Hello from MyBean!"); // 출력: Hello from MyBean!
    }
}

MyBean 클래스


ClassPathXmlApplicationContext(String[] paths, Class<?> clazz, ApplicationContext parent)

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="sharedBean" class="com.example.SharedBean">
        <property name="message" value="This is a shared bean."/>
    </bean>
</beans>

parentContext.xml

  • bean id 는 beanFactory에서 관리하는 고유 식별 id 이므로 변수명과는 다르다.
  • property name="message"는 setmessage 는 스프링은 내부적으로 JavaBeans 명명 규칙을 사용하여 name 속성 값에 해당하는 setter 메서드를 호출합니다.
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="childBean" class="com.example.ChildBean">
        <property name="sharedBean" ref="sharedBean"/>
    </bean>
</beans>

childContext.xml

package com.example;

public class ChildBean {
    private SharedBean sharedBean;

    public void setSharedBean(SharedBean sharedBean) {
        this.sharedBean = sharedBean;
    }

    public void printMessage() {
        System.out.println(sharedBean.getMessage()); 
    }
}


class SharedBean {
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

자식 클래스 정의

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        // 부모 컨텍스트 생성
        ApplicationContext parentContext = new ClassPathXmlApplicationContext(new String[]{"parentContext.xml"}, Main.class);

        // 자식 컨텍스트 생성, 부모 컨텍스트를 설정
        ApplicationContext childContext = new ClassPathXmlApplicationContext(new String[]{"childContext.xml"}, Main.class, parentContext);

        // 자식 컨텍스트의 빈 가져오기
        ChildBean childBean = (ChildBean) childContext.getBean("childBean");
        childBean.printMessage(); // 출력: This is a shared bean.
    }
}

java 코드


차이점은 자식 클래스에서 부모 클래스 인스턴스를 생성 후 해당 부모 Bean을 설정 시, 오류 없이 자식 객체에서 부모 객체를 사용할 수 있다. 즉 위에서 설명한 "부모 컨텍스트를 지정하면, 부모 컨텍스트에서 정의된 빈을 자식 컨텍스트에서 사용할 수 있습니다." 의미이다.

profile
효율적인 시스템 설계를 고민하며, 확장성과 안정성을 갖춘 백엔드 개발자가 되길 희망합니다.

0개의 댓글