1. 스프링 컨테이너(Spring Container)

  • ApplicationContext 를 스프링 컨테이너라고 한다
  • 인터페이스로 구현되어 있고, 다형성이 적용된다
  • XML, 애너테이션 기반의 자바 설정 클래스로 만들 수 있다
  • 이전까지는 개발자가 xml을 통해 모두 설정하여야 했으나, Spring Boot를 사용하면서 설정하지 않는다
  • 빈의 인스턴스화, 구성, 전체 생명 주기 및 제거까지 처리한다
    - 컨테이너는 개발자가 정의한 Bean을 객체로 만들어 관리하며, 개발자가 필요로 할 때 제공한다
  • 스프링 컨테이너를 통해 원하는 만큼 객체를 가질 수 있다
  • 의존성 주입을 통해 애플리케이션의 컴포넌트를 관리한다
    - 스프링 컨테이너는 서로 다른 빈을 연결해 애플리케이션의 빈을 연결하는 역할을 한다
    - 개발자는 모듈 간에 의존 및 결합으로 인해 발생하는 문제로부터 자유로울 수 있다
    - 메서드가 언제, 어디서 호출되어야 하는지, 메서드를 호출하기 위해 필요한 매개 변수를 준비해서 전달하지 않는다

2. Spring Container 사용 목적

 

Spring Framework - IoC / DI - 기초 :: 상상코딩

 

coding-mid-life.tistory.com

  • 객체 간의 의존성을 낮추기 위하여 사용한다
  • 새로운 정책이 발생할 경우 변경 사항을 수작업으로 해야 한다
  • 코드의 양이 방대할 경우 수정 시간이 과도하게 소모된다
  • 스프링 컨테이너를 사용할 경우 인터페이스에만 의존하도록 설계할 수 있다

 

3. Spring Container 생성

  • 기존에는 xml방식으로 설정하였다 (ClassPathXmlApplicationContext)
<?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">
        <-- <beans />에 필요한 값들을 설정합니다. -->
        
    <bean id="..." class="...">  
        <!-- id="..." Bean의 정의를 식별하는 문자열을 작성한다 -->
        <!-- class="..." Bean의 유형을 정의하고 클래스 이름은 작성한다 -->
    </bean>
         
    <bean id="..." class="...">         
   		 <!-- 추가적인 Bean을 작성한다 -->
    </bean>    
</beans>
  • 최근에는 주로 애너테이션 기반의 자바 설정 클래스로 Spring Container 을 만드는 것을 의미한다
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);


스프링 컨테이너를 만드는 다양한 방법은 ApplicationContext 인터페이스의 구현체이다
 - AppConfig.class 등의 구성 정보를 지정해줘서 스프링 컨테이너를 생성한다
 - AppConfig에 있는 구성 정보를 통해서 스프링 컨테이너는 필요한 객체들을 생성한다
 - 애플리케이션 클래스는 구성 메타데이터와 결합되어 ApplicationContext 생성 및 초기화된 후
   완전히 구성되고 실행 가능한 시스템 또는 애플리케이션을 갖게 된다
  • 스프링 컨테이너는 Configuration Metadata를 사용한다
  • 스프링 컨테이너는 파라미터로 넘어온 설정 클래스 정보를 사용해서 스프링 빈을 등록한다
  • new AnnotationConfigApplicationContext(구성정보.class)로 스프링에 있는 @Bean의 메서드를 등록한다
    ※  주석 기반 컨테이너 구성
       : https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-annotation-config
  • 스프링 빈 조회에서 상속관계가 있을 시 부모타입으로 조회하면 자식 타입도 함께 조회된다
    - 모든 자바 객체의 최고 부모인 object타입으로 조회하면 모든 스프링 빈을 조회한다

※ IntelliJ 에서 ApplicationContext 인터페이스를 확인하는 방법

  - ctrl + n >  class >  ApplicationContext 입력 검색

  -  ApplicationContext 인터페이스를 구현하기 위한 하위 클래스를 확인할 수 있다

 

 

4. Spring Container 종류

  • 파라미터로 넘어온 설정 클래스 정보를 참고해서 빈의 생성, 관계 설정 등의 제어작업을 총괄하는 컨테이너이다

 1) BeanFactory

  • 스프링 컨테이너의 최상위 인터페이스이다
  • BeanFactory는 bean을 등록, 생성, 조회, 반환 등... 빈을 관리하는 역할을 한다
  • getBean() 메소드를 통해 빈을 인스턴스화 할 수 있다
  • @Bean이 붙은 메서드의 이름을 스프링 빈의 이름으로 사용해 빈을 등록한다

 2) ApplicationContext

  • BeanFactory의 기능을 상속받아 제공한다
  • bean을 관리하고 검색하는 기능을 BeanFactory가 제공하고 그 외에 부가기능을 제공한다
  • 부가 기능은 아래와 같다
    - MessageSource: 메세지 다국화를 위한 인터페이스
    - EnvironmentCapable: 개발, 운영 등 환경변수 등으로 나눠 처리하고, 애플리케이션 구동 시 필요한 정보들을 관리하기 위한 인터페이스
    - ApplicationEventPublisher: 이벤트 관련 기능을 제공하는 인터페이스
    - ResourceLoader: 파일, 클래스 패스, 외부 등 리소스를 편리하게 조회

5. Container 인스턴스화

  • ApplicationContext 생성자에 제공된 위치 경로는 컨테이너가 로컬 파일 시스템, Java CLASSPATH 등과 같은 다양한 외부 리소스로부터 구성 메타데이터를 로드할 수 있도록 하는 리소스 문자열이다
// Annotation
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

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

 

6. new 와 생성자 주입

  • new를 사용하는 대신 생성자를 통해 의존 객체가 주입되고, 느슨한 의존 관계가 이루어진다

  • userRepository와 discountInfo의 구현 클래스는 Bean 설정에 따라서 유연하게 변하게 된다
  • OrderServiceImpl 클래스는 생성자를 통해 어떤 구현 객체가 주입될지 알 수 없으며, 알 필요도 없다
  • 어떤 객체가 주입될지는 외부 AppConfig에서 결정된다
  • OrderServiceImpl 클래스는 실행에만 집중하게 된다

7. 빈(Bean)

  • 스프링 컨테이너에 의해 관리되는 재사용 소프트웨어 컴포넌트이다
    - 컴포넌트(component) : 여러 개의 객체를 하나로 묶어서 저장한 그룹
  • Spring 컨테이너가 관리하는 자바 객체를 의미하며, 하나 이상의 빈을 관리한다
  • Bean은 인스턴스화된 객체를 의미한다
  • 스프링 컨테이너에 등록된 객체를 Spring Bean 이라고 한다
  • @Bean이 적힌 메서드를 모두 호출해서 반환된 객체를 스프링 컨테이너에 등록한다
  • Bean은 클래스의 등록 정보와 getter/setter 메서드를 포함한다
  • Bean은 컨테이너에 사용되는 설정 메타데이터로 생성된다
  • 설정 메타데이터
    - XML, Java annotation, Java code 로 표현한다
    - 컨테이너의 명령, 인스턴스화, 설정, 조립할 객체 를 정의한다

 1) Bean 접근 방법

  • ApplicationContext 사용하여 bean 정의를 읽고 액세스할 수 있다
// bean을 생성하고 구성한다
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

// getBean 메서드로 bean 인스턴스를 가져온다
PetStoreService service = context.getBean("cmarket", cmarketService.class);

// bean 인스턴스를 사용한다
List<String> userList = service.getUsernameList();
  • 응용 프로그램 코드에서는 getBean() 메서드로 호출하여 사용하면 안된다

 2) Bean의 정의(BeanDefinition)

  • 스프링은 다양한 설정 형식을 BeanDefinition이라는 추상화 덕분에 지원할 수 있다
  • Bean은 BeanDefinition에 의해 정의되며, BeanDefinition에 따라 활용하는 방법이 달라진다
  • BeanDefinition (빈 설정 메타정보)
    - 속성에 따라 컨테이너가 Bean을 어떻게 생성하고 관리할지를 결정한다
    - @Bean or <bean> 당 각 1개씩 메타 정보가 생성된다
    - Spring은 설정 메타정보를 BeanDefinition 인터페이스를 통해 관리하기 때문에 컨테이너 설정을 XML, Java로 할 수 있다
    - 스프링 컨테이너는 설정 형식이 XML인지 Java 코드인지에 상관없이 BeanDefinition만 알면 된다

※ BeanDefinition

 : https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/config/BeanDefinition.html

 

BeanDefinition (Spring Framework 5.3.21 API)

Return the current bean class name of this bean definition. Note that this does not have to be the actual class name used at runtime, in case of a child definition overriding/inheriting the class name from its parent. Also, this may just be the class that

docs.spring.io

 

참조 링크

▶ 컨테이너 : https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-basics

 

Core Technologies

In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do

docs.spring.io

빈 : https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-definition

 

Core Technologies

In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do

docs.spring.io

 XML 스키마 기반 구성 : https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/html/xsd-configuration.html

 

40. XML Schema-based configuration

First up is coverage of the util tags. As the name implies, the util tags deal with common, utility configuration issues, such as configuring collections, referencing constants, and suchlike. To use the tags in the util schema, you need to have the followi

docs.spring.io

 config.xml 개요 : https://docs.oracle.com/cd/E13222_01/wls/docs81b/config_xml/overview.html

 

Overview of config.xml

 

docs.oracle.com

▶ XML 관련 문서 google 추천 검색어 : "beans xmlns meaning" 또는 "xml configuration"

'Spring Framework' 카테고리의 다른 글

Spring Framwork - PSA(Portable Service Abstraction)  (0) 2022.06.22
Spring Framework - AOP  (0) 2022.06.22
Spring Framework - IoC / DI - 기초  (0) 2022.06.17
Spring Framework 특징  (0) 2022.06.15
Spring Framework - 정의  (0) 2022.06.15

+ Recent posts