ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스프링 컨테이너에 대한 개념
    Spring Framework 2023. 10. 4. 19:19

    스프링 컨테이너(Spring Container)

    • 자바 객체의 생명 주기를 관리
    • 생성된 bean에게 추가적인 기능을 제공한다.
    • 객체가 의존관계를 등록할 때는 스프링 컨테이너에서 해당하는 빈을 찾고, 그 빈과 의존성을 만듭니다.
    • @Autowired같은 DI가 정상적으로 동작하려면 인스턴스가 bean으로써 스프링 컨테이너에 들어가있어야 합니다.

     

    스프링 컨테이너(Spring Container)의 종류

    * Spring Container는 Configuration Metadata를 사용하고, 파라미터로 넘어온 설정 클래스 정보를 사용해 Spring Bean을 등록한다

    1. BeanFactory
      • bean의 생성과 관계설정 같은 제어를 담당하는 IOC 오브젝트
      • Spring Container의 최상위 인터페이스
      • getBean() 메서드를 통해 빈을 인스턴스화 할 수 있다.
      • @Bean 어노테이션이 붙은 메서드의 이름을 스프링 빈의 이름으로 사용하여 빈 등록을 한다.
    2. ApplicationContext
      • BeanFactory를 확장한 인터페이스
      • 주로 사용되는 Spring Container
      • 메시지 다국화를 위한 인터페이스가 존재 (MessageSource)
      • 개발, 운영, 환경변수 등으로 나누어 처리하고, 애플리케이션 구동 시 필요한 정보들을 관리하기 위한 인터페이스가 존재 (EnvironmentCapable)
      • 이벤트 관련 기능을 제공하는 인터페이스가 존재 (ApplicationEventPublisher)
      • 파일, 클래스 패스, 외부 등 리소스를 편리하게 조회하는 기능 존재 (ResourceLoader)

     

    스프링 컨테이너(Spring Container) 생성

    • ApplicationContext 인터페이스의 구현체를 통해 다양한 방법으로 생성된다.
    • AppConfig.class 등의 구성 정보를 지정하여 Spring Container를 생성할 수 있다.
    • 메타데이터와 애플리케이션 클래스가 결합해 ApplicationContext를 생성하고 초기화해 애플리케이션을 실행
    • Object 타입을 이용하면 모든 spring bean을 조회할 수 있다.
    /*
        ApplicationContext를 스프링 컨테이너라고 하며, 인터페이스로 구현되어 있다.
        AnnotationConfigApplicationContext는 ApplicationContext 인터페이스의 구현체 중 하나이다.
        @Configuration : 스프링 컨테이너가 해당 어노테이션이 붙은 클래스를 설정 정보로 사용한다.
        @Bean 어노테이션이 적힌 메서드를 모두 호출하여 얻은 객체를 스프링 컨테이너에 등록하게 된다.
        applicationContext.getBean(”이름”, class타입); : 스프링 bean을 얻을 수 있다.
    */
    // 스프링 컨테이너 생성
    public class App {
        public static void main(String[] args) {
            ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
            BoardService boardService = applicationContext.getBean("boardService", BoardService.class)
        }
    }
    
    // 컨테이너 구성 및 등록
    @Configuration
    public class AppConfig {
    
        @Bean
        public BoardService boardService() {
            return new BoardServiceImpl(boardRepository());
        }
    
        @Bean
        public BoardRepository boardRepository() {
            return new MemoryBoardRepository();
        }
    }
    • ApplicationContext의 구현체로는 AnnotationConfigApplicationContext()가 있기 때문에 AnnotationConfigApplicationContext의 매개변수에 구성정보로 AppConfig.class와 같은 Bean을 정의한 @Configuration 클래스를 넣어주면 된다.

     

    참고) XML 기반으로 컨테이너 구성 및 생성

    /*
        XML 기반으로 만드는 ClassPathXmlApplicationContext도 있다.
      
        <beans /> 태그를 통해 필요한 값들을 설정할 수 있다.
        <bean id=”…”> 태그는 빈 정의를 식별하는 데 사용하는 문자열이다.
        <bean class=”…” 태그는 Bean의 유형을 정의하고 클래스 이름을 사용한다.
    */
    
    // xml 방법으로 컨테이너 생성
    ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
    
    // xml 기반 메타데이터 기본구조
    <?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>

     

    스프링 컨테이너(Spring Container)의 필요성

    • 객체를 생성하려면 new 생성자를 사용하는데, 그렇다면 애플리케이션에는 많은 객체들이 서로를 참조한다. 참조가 많아지게 된다면 의존성이 높아진다. (낮은 결합도와 높은 캡슐화를 지향하는 객체지향과는 거리가 멀다.)
    • 객체의 의존성을 낮춰 객체지향의 핵심인 낮은 결합도 / 높은 캡슐화를 하기 위해 스프링 컨테이너가 사용된다.

     

    출처)

    https://velog.io/@tank3a/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%BB%A8%ED%85%8C%EC%9D%B4%EB%84%88%EC%99%80-%EC%8A%A4%ED%94%84%EB%A7%81-%EB%B9%88

    https://ittrue.tistory.com/220

Designed by Tistory.