본문 바로가기
Spring

Dependency Injection ( XML )

by Coarti 2023. 6. 14.

( 이전 글과 이어지는 내용입니다. https://cloakinghost.tistory.com/7 )

 

spring.di 패키지에 Spring Bean Definition file을 생성

setting.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 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

</beans>

앞서 main함수 부분에서 선언한 부분을 xml을 사용하여 바꿔보록하자

xml 지시서를 사용하여 객체 생성과 조립을 요청할 것이다

 

 이전 게시글 main함수의 일부이다

Exam exam = new ScoreExam(); // 바뀔 여지가 있다 설정으로 빼야한다
ExamConsole console = new GridExamConsole(); // Dependency // 바뀔 여지가 있다 설정으로 빼야한다
console.setExam(exam); // Injection // 결합관계도 바뀔 수 있다

주석의 내용처럼 수정의 여지가 있는 부분은 지시서로 빼내어 따로 관리하도록 하자

<beans (생략)>

	<!-- Exam exam = new NewlecExam(); -->
	<bean id="exam" class="spring.di.entity.NewlecExam" />
	
	<!-- ExamConsole console = new GridExamConsole(); -->
	<bean id="console" class="spring.di.ui.InlineExamConsole" >
	<!-- console.setExam(exam); -->
		<property name="exam" ref="exam"/>
	</bean>
    
</beans>

사용방법 : <beans> 내용작성 </beans>

 

주석으로 되어있는 자바코드와 비교해보자

 

첫번째 bean

id = 변수명 /  class = 임포트 되어있는 클래스의 위치를 작성하였다 ( 동일한 이름의 클래스와 충돌을 방지 )

 

두번째 bean

id, class는 동일한 방법으로 사용되었다

여기서 봐야할 것은 'property' 부분이다

name = 함수의 이름이 들어간다

이때 Setter를 사용하여 값을 초기화 해주는데 Setter함수가 사용되고 있는 필드명을 기재한다. 즉, setter함수가 없으면 안된다는 것이다 ( BeanCreationException 발생 )

 

값을 직접 넣어주는 태그로 ref, value 2가지가 있다

ref = 인스턴스인 경우 ( bean의 id )

value = 기본타입인 경우

 

 

작성 방법을 바탕으로 첫번쨰 bean에 초기값을 주도록하자

	<bean id="exam" class="spring.di.entity.ScoreExam">
		<property name="kor">
			<value>10</value> <!-- <ref bean="xml에 기재한 id 입력"/>도 있음 -->
		</property>
		<property name="eng" value ="10"/>
		<property name="math" value ="10"/>
		<property name="com" value ="10"/>
		
	</bean>

지시서를 작성하였으니 불러올수 있도록 해보자

 

( 내용이 길어지는 관계로 다음글에서 실습해보자 )

728x90

'Spring' 카테고리의 다른 글

@Autowired, @Qualifier 사용법  (0) 2023.08.05
XML 사용법  (0) 2023.08.05
Inversion of Control Container ( Ioc Container )  (0) 2023.06.14
Dependency Injection ( 순수 Java )  (0) 2023.06.14
Dependency Injection ( DI )  (0) 2023.06.13