Framework/Spring

[Spring] 스프링의 IoC Container가 뭘까?

KOOCCI 2022. 7. 23. 01:23

목표 : 스프링의 IoC Container 에 대해 설명할 수 있다.


앞선 포스팅에서 스프링 프레임워크가 주는 의문 두가지,

  1. 스프링은 무엇을 도와주는가?
  2. 스프링의 사용법은 어떻게 되는가?

중에서 스프링의 사용법은 어떻게 되는지 알아볼 차례다.

 

일단 그 전에, 용어를 정리해야 사용법도 알게 될 것이므로 용어부터 하나씩 보도록 하자.

그 중, IoC Container 에 대해 알아볼 것이고, 그 내용은 스프링 공식 문서를 기반으로 확인해 보겠다.

 

스프링 코어 (spring-core)

스프링 코어의 가장 처음 나오는 용어가 IoC Container 이다.

그리고 그 문장을 그대로 가져오면 다음과 같다.

Foremost amongst these is the Spring Framework’s Inversion of Control (IoC) container.

스프링 프레임워크의 가장 중요한 것은 Inversion of Control(IoC) container 다.

그리고 IoC는 Dependency Injection(DI, 종속성 주입) 이라고도 하는데 그 설명을 읽어보면 바로 직관적으로 와닿지 않는다.

그렇기에 우선은 간략하게 아래 처럼 이해해보자.

 

스프링 프레임워크는 ApplicationContext라는 인터페이스를 통해서 IoC Container 를 제공하고 있다.

org.springframework.context.ApplicationContext 가 IoC Container 의 핵심인데, 이 인터페이스를 기준으로 구현된 다양한 구현체를 통해서 다양한 방식, 다양한 방법으로 IoC Container 기능이 구현되어 있다.

 

뭔지 모르겠지만, ApplicationContext라는 친구가 스프링 프레임워크의 IoC Container 를 책임지고 있는 것 같다.

그리고 아래 이미지를 보며 좀더 구체적으로 이해해보자.

 

https://docs.spring.io/spring-framework/docs/current/reference/html/images/container-magic.png
Figure 1. The Spring IoC Container

POJO(Plain Old Java Object)로 만들어진 나의 비즈니스 오브젝트(나의 소스코드, 객체들)들은

스프링에서 제공하는 방법에 따라 만들어준 설정정보(Configuration Metadata) 결합되고,

Application Context를 구현한 구현체(Spring Container)가 생성되고 초기화되었을 때, 실행가능한 프로그램(스프링에서 구동가능한 형태)이 되는 것이다.

 

번역하다보니 어렵지만, 결국 프레임워크 설명과 유사하다.

내가 만든 소스코드가 잘 작성된 설정정보랑 합쳐지면, Application Context의 구현체가 스프링에서 동작 가능하도록 만들어준다는 것이다.

 

그럼 먼저, 설정 정보라는 것이 무엇인지 보자.

 

Configuration Metadata

스프링에서 제공하는 설정방법은 크게 2가지, XMLAnnotation이다.

먼저 XML 예시를 보도록 하자. (Annotation은 나중에 다시 볼 것이다)

<?xml version="1.0" encoding="UTF-8"?>
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="..." class="...">  
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>

설명에서는 계속 등장했었지만, 뭔지 몰라도 Bean이라는게 설정 정보에도 등장했다.

일단 위와 같은 형태로 작성한다는 내용을 인지하고, ApplicationContext 설명부터 보자.

 

ApplicationContext 인스턴스화

ApplicationContext는 인터페이스고 그 구현체가 필요하다.

앞서 말했듯이 구현된 다양한 구현체를 통해서 다양한 방식, 다양한 방법으로 IoC Container 기능을 구현하기 때문이다.

 

그 예시로 다음을 들고 있다.

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

여기서는 ClassPathXmlApplicationContext 라는 구현체를 사용했다.

그 Argument로는 services.xml과 daos.xml을 넣어주고 있다. (그 예시 역시 해당 페이지에 나온다)

 

이제 앞선 설정정보와 연결해서 보도록 하자.

 

Bean은 뭐고, ApplicationContext, Configuration Metadata랑 어떻게 연결되는 거지?

Spring Framework에서는 Bean이라는 것을 만든다.

쉽게 생각하면 객체다. 

이 객체를 관리하는 것 Container다.

 

다시 말해, Bean Spring Container (ApplicationContext 구현체) 가 관리하고 생성하고 인스턴스화 해주는 객체다.

 

보통 우리가 java에서 객체를 만들고 사용할 때는 다음 문장처럼 작성한다.

MyObject obj = new MyObject():

그러나 위처럼 직접 객체를 만들어주지않고, 설정정보에 작성하면 Spring Framework가 이 객체를 관리/생성/인스턴스화 하게 된다.

<?xml version="1.0" encoding="UTF-8"?>
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="com.text.myObject"/>  

</beans>

이처럼 설정 정보에 작성해준다면, MyObject 클래스를 더이상 new 로 생성하지 않고, ApplicationContext로부터 얻어오는 것이다.

ApplicationContext context = new ClassPathXmlApplicationContext("myObject.xml"); // 설정정보
MyObject obj = context.getBean(MyObject.class);
obj.method(); // 행위

위 과정을 다시한번 정리해보자.

Spring Framework에서, ApplicationContext의 구현체인 Spring Container는 Bean이라는 것으로 사용하고자 하는 객체를 관리한다.
그 생성과 인스턴스화를 관리하며, Bean에 대한 정보는 Configuration Metadata를 통해 정의한다.

그럼 마지막, IoC Container에 대해 정리하며 마무리하도록 하자.

Wrap Up

Spring Framework에서는 ApplicationContext를 통해 IoC Container를 제공하고 있다.

ApplicationContext는 인터페이스이며, 그 구현체는 Spring Container(=IoC Container)라고 한다.

Spring Container는 Bean이라고 하는 사용하고자 하는 객체의 생성, 인스턴스화 등을 관리하고 있다.

Bean에 대한 정보는 Configuration Metadata에 정의하여 관리된다.

 

Configuration Metadata에 정의된 Bean이라는 객체를 관리하고 생성을 책임지고 인스턴스화 하는 ApplicationContext의 구현체인 Spring ContainerIoC Container 라고 하며, Spring Framework에게 객체에 대한 관리,제어를 넘겨 주는 것을 제어의 역전(Inversion of Control, IoC) 라고 한다.