"프레임 워크 개요-(2)에서는 개발자가 직접 클래스(삼성 티비,LG 티비)를 생성하여, 클라이언트에서 활용했다. (3)에서는 스프링 설정 파일(* Spring Bean Configuration)을 생성하여, 컨테이너를 통해 객체를 설정해본다."
3.1 스프링 IoC 시작하기(P49)
3.1.1 스프링 설정 파일 생성
1) 스피링 컨테이너 : 대부분의 IOC 컨테이너(* 객체들을 생성해주는 역할)는 각 컨테이너에서 관리할 객체들을 위한 별도의 설정 파일이 있다.
2) 스프링 별도의 설정 파일 생성
: 프로젝트 - src/main/resource - 마우스 우측 버튼 - new/other - "Spring Bean Configuration"
(* Spring에서는 Spring Bean Configuration이 스프링 별도 설정 파일이다.)
3) " Spring Bean Configuration " 생성
<?xml version="1.0" encoding="UTF-8"?>
<!-- 스프링 컨테이너 / IOC는 결국 클래스로부터 객체를 자동으로 생성하는 것이다. -->
<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">
<!-- 1. <bean id="tv" class="polymorhism_inter.Samsung" init-method="initMethod"/>-->
<!-- 2. <bean id="tv" class="polymorhism_inter.Samsung" destroy-method="destoyMethod"/> -->
<!-- 3. <bean id="tv" class="polymorhism_inter.Samsung" scope="singleton"/>-->
<!-- 4. <bean id="tv" class="polymorhism_inter.Samsung" scope="prototype"/>-->
<bean id="tv" class="polymorhism_inter.Samsung"/>
</beans>
- 위의 .xml은 스프링 설정 파일이고 해당 소스를 통해 현재는 samsung이라는 객체를 id = "tv"라는 별명으로 지정하였다. (*samsung 클래스의 내용은 프레임 워크 개요 - (2) 참조)
- .xml 방식을 통해 <bean id="tv" class="polymorhism_inter.Samsung"/> 객체를 생성(*Lookup)하였다.
해당 역할은 스프링 컨테이너의 중요한 핵심 기능 2개중 1가지이다.
- 1~4는 .xml의 <bean> 엘리먼트에 대한 속성 들이다.(p59 참조)
4) 스프링 컨테이너 구동 및 테스트
package polymorhism_inter;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
/*
* Spring 컨테이너 실습하기 위한 클라이언트
* */
public class TVUser_IOC {
public static void main(String[] args) {
// 1. Spring 컨테이터 구동 GenricXmlApplicationContext는 객체를 PreLoading 하는 Context이다.
AbstractApplicationContext factory = new GenericXmlApplicationContext("applicationContext.xml");
// 2. Spring 컨테이너가 필요한 객체를 요청(Lookup)한다.
TV tv = (TV) factory.getBean("tv");
tv.powerOn();
tv.volumeUp();
tv.volumeDown();
tv.powerOff();
// 3. Spring 컨테이너를 종료한다.
factory.close();
}
}
"이 책 공부하기 전까지는 .xml 파일이 스프링 컨테이너 인 줄 알았는데, 위의 GenericXmlApplication이 스프링 컨테이너이고 .xml은 단지 컨테이너가 사용할 수 있는 객체를 생성해주는 설정파일에 불과했다 .. ㅠㅠ;;"
[스프링 작동 원리]
스프링 컨테이너 작동 원리는 대략적으로 다음과 같다.
1) TV_Client가 스프링 설정파일 로딩과 동시에 컨테이너 구동한다.
2) 스프링 설정 파일에 객체들을 생성한다.
3) TV_Client에서 id 값을 통해 객체를 요청한다.
4) 해당 객체 반환
'자바 > SpringFrameWork' 카테고리의 다른 글
[스프링퀵스타트1-4] : 의존성 주입-(2) (0) | 2020.05.22 |
---|---|
[스프링퀵스타트1-4] : 의존성 주입-(1) (0) | 2020.05.19 |
[스프링퀵스타트1-2] 프레임 워크 개요-(2) (0) | 2020.05.16 |
[스프링퀵스타트1-2] 프레임 워크 개요-(1) (0) | 2020.05.16 |
[스프링퀵스타트] D1-실습 프로젝트 생성 (0) | 2020.05.15 |