Spring 02 ApplicationContext, Spring Bean Configuration File

Kang.__.Mingu·2024년 9월 7일

Spring

목록 보기
2/21
post-thumbnail

CreateBean.java(class)

  • 사진과 같이 기본생성자와 display 메서드를 정의해논다.

CreateBeanApp.java(실행 프로그램)

04-1_beanCreate.xml(ApplicationContext 환경설정 파일)


ApplicationContext 객체를 생성하여 Spring Container로 사용하는 방법

(Spring Container 초기화 전)

  • ApplicationContext(Spring Container) 인터페이스를 상속받은 자식클래스로 객체 생성 => ApplicationContext 객체

  • ApplicationContext는 객체를 생성할 때 환경설정파일 (Spring Bean Configuration File)을 제공받아 ApplicationContext 객체를 초기화 처리한다.

  • ApplicationContext 객체는 환경설정파일에 등록된 클래스로 미리 객체가 생성되어진다.

ApplicationContext context=
	new ClassPathXmlApplicationContext("04-1_beanCreate.xml");

(Spring Container 초기화 후)

  • ApplicationContext.getBean(String beanName): 매개변수로 Spring Bean를 구분하기 위한 식별자(beanName)을 전달받아 스프링 컨테이너로부터 객체를 반환하는 메소드
  • Object 타입의 객체를 반환하므로 반드시 명시적 객체 형변환을 사용해야한다.
  • 매개변수로 전달받은 식별자(beanName)가 없는 경우 NoSuchBeanDefinitionException 발생
  • getBean() 메소드로 가져올 때 DL(Dependency Lookup)이 발생한다.
    • DL은 스프링 컨테이너가 관리하는 클래스(Spring Bean)을 검색하여 객체를 제공하는 기능이다.
CreateBean bean2=(CreateBean)context.getBean("createBean");
bean2.display();
  • 해당 객체를 가져와 사용하고 항상 Spring Container를 소멸시켜야한다.

getBean 메소드를 호출하여 형변환까지 하기

ApplicationContext.getBean(String beanName, Class class)

  • 매개변수로 식별자(beanName)를 전달받아 스프링 컨테이너로부터 객체(Spring Bean)를 제공받아 객체 형변환하여 반환하는 메소드
// getBean(xml파일에서 호출할 식별자, 형변환할 클래스)
InitDestroyMethodBean bean=context.getBean("initDestroyMethodBean", InitDestroyMethodBean.class);

Spring Bean Configuration File(환경설정파일)을 여러개 작성하는 이유는?

Spring Bean Configuration File을 하나만 작성하여 사용할 경우 가독성 및 유지보수의 효율성이 감소된다.

  • 다른 파일에 있는 Spring Bean 환경설정 파일을 가져올 때는 import 태그를 사용하면 된다.
  • import: 다른 Spring Bean COnfiguration File의 정보를 제공받아 포함하기 위한 엘리먼트이다.
  • resource 속성: Spring Bean Configuration File의 경로를 속성값으로 설정
<import resource="03_message.xml"/>

Spring Bean Configuration File(환경설정파일)에 bean 등록하는 방법

  • bean : 스프링 컨테이너에게 객체(Spring Bean) 관련 정보를 제공하기 위한 엘리먼트

    • Spring Bean: 스프링 컨테이너에 의해 관리(생성, 제공, 소멸)되는 클래스
  • class 속성: 스프링 컨테이너에 의해 관리될 클래스를 속성값으로 설정 [필수]

    • class 속성값은 자동 완성 기능을 사용해 작성 가능하다. 해당 클래스만 입력하고 ctrl+space
  • id 속성: Spring bean을 구분하기 위한 식별자(beanName)를 속성값으로 설정

    • id 속성 대신 name 속성을 사용하여 식별자 설정 가능하다.

    • id 속성값은 클래스(인터페이스)의 이름을 이용하여 작성하는 것을 권장

    • class 속성을 먼저 작성한 경우 id 속성은 자동 완성 기능을 사용해 작성 가능하다.

<bean class="xyz.itwill04.bean.CreateBean" id="createBean"/>
  • init-method 속성: 객체(Spring Bean)을 생성 후 초기화 처리하기 위해 자동 호출될 메소드의 이름을 속성값으로 설정
  • destory-method 속성: 객체(Spring Bean)을 소멸 전 마무리 처리하기 위해 자동 호출될 메소드의 이름을 속성값으로 설정
	<bean class="xyz.itwill04.bean.InitDestroyMethodBean" 
          id="initDestroyMethodBean"
		init-method="init" destroy-method="destroy"/>
  • lazy-init 속성: false(기본값) 또는 true 중 하나를 속성값으로 설정
    • false: 스프링 컨테이너가 초기화될 때 객체를 미리 생성
    • true: 스프링 컨테이너가 초기화될 때 객체를 미리 생성하지 않고 getBean() 메소드를 호출할 때 객체를 생성하여 제공
profile
최선을 다해 꾸준히 노력하는 개발자 망고입니당 :D

0개의 댓글