[Spring] XML 기반 컨테이너 구성

2023. 10. 24. 19:33
728x90

** 전과 같이 MyRoom (main) + Tape + TapeReader 클래스 활용.

- MyRoom main --> XML 기반 컨테이너 구성

- Tape --> getter, setter 설정

- TapeReader --> setTape 설정

 

1. Setter 기반 주입

1) setter-config.xml 파일 생성

  • 해당 링크에서 beans 태그 가지고오기 
  • bean : 서비스에서 사용되는 비즈니스 객체. 현재 맥락에서는 TapeReader, Tape...
  • bean 생성 id = 해당 bean의 고유한 이름
  • class = 해당 bean의 타입 (패키지 포함 풀네임)
<?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.xsd">       

	<bean id = "tapeReader" class = "dev.spring.step01setter.TapeReader">
		<property name="tape" ref="tape"/>
	</bean>
	
	<bean id = "tape" class = "dev.spring.step01setter.Tape">
		<property name = "name" value = "아일랜드"/>
		<property name = "worked" value = "true"/>	
	</bean>
</beans>

2) MyRoom 클래스에서 xml 기반 컨테이너 구성.

context 프로그램이 돌아가면서 기저에서 돌고 있는 설정 값들이나 정보들을 xml 파일에 설정하고, 스프링 컨테이너를 생성하면서 설정 정보가 담긴 xml 파일을 전달! 

=> ApplicationContext context = new ClassPathXmlApplicationContext("setter-config.xml");

package dev.spring.step01setter;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyRoom {

	public static void main(String[] args) {
		// 1. XML 기반 컨테이너 구성
		ApplicationContext context = new ClassPathXmlApplicationContext("setter-config.xml");
		
		TapeReader reader = context.getBean(TapeReader.class);
		reader.test();
	}
}

* Tape (setter/getter+출력문)

package dev.spring.step01setter;

public class Tape {
	private String name; // 테이프 이름
	private boolean isWorked; // 정상 동작 여부

	public Tape() {
		super();
		System.out.println("Tape() called");
	}

	public Tape(String name, boolean isWorked) {
		super();
		this.name = name;
		this.isWorked = isWorked;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		System.out.println("setName(String name) called()");
		this.name = name;
	}

	public boolean isWorked() {
		return isWorked;
	}

	public void setWorked(boolean isWorked) {
		System.out.println("setWorked(boolean isWorked) called()");
		this.isWorked = isWorked;
	}

}

* TapeReader (test 메서드와 setTape 메서드)

package dev.spring.step01setter;


public class TapeReader {

	private Tape tape;

	public void test() {

		if (tape.isWorked()) {
			System.out.println(tape.getName() + " 정상 동작합니다");
		} else {
			System.out.println(tape.getName() + " 사기 당했습니다");
		}

	}

	// setter 기반 의존성(Tape) 주입(Injection)
	public void setTape(Tape tape) {
		this.tape = tape;
	}

	@Override
	public String toString() {
		return "TapeReader 입니다.";
	}

}

종합해보면... xml 파일에 기저 설정을 해놓는다 > 요때 bean을 만든다 

bean 1. TapeReader 클래스 경로 설정과 함께 안에 property태그로 Tape 객체를 주입이 가능.

bean 2. Tape 객체를 클래스 경로 설정과 함께 bean 만들고, 각 필드의 value값을 설정해준다 (** 이 때 isWorked의 name은 setter의 이름을 따라 setWorked 에서 worked를 따옴.**)

이렇게 bean이 생성이 된 상태에서 메인 클래스에서 컨테이너를 선언하고 xml 파일을 전달해주면 bean들이 context로 들어가서 

context.getBean(TapeReader.class) 메서드 사용 가능.

출력문 순서를 보면 어떤 흐름인지 이해가 간다. 

 

출력문 순서 !

- Tape() called // Tape tape 생성 순간

- setName(String name) called() // Tape tape 생성 후 name setting

- setWorked(boolean isWorked) called() // Tape tape 생성 후 worked setting

- TapeReader 입니다.  // TapeReader toString() 메서드 실행

- 아일랜드 정상 동작합니다. // TapeReader test() 메서드 실행

 

이 방식이 setter 기반으로 의존성 주입한 것.

 

 

2. 생성자 기반 주입

1) constructor-config.xml 파일 생성

이것도 마찬가지로 xml 파일 설정부터 한다.  똑같이 beans xmlns... 기초 설정과 bean 두가지를 만들어 주기.

이 땐 setter 주입이 아니므로 다른 태그를 쓴다!! 생성자 주입은 constructor-arg

Tape 객체에 생성자 주입은 type과 value를 쓰면 된다.

<?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.xsd">

	<bean id="tapeReader"
		class="dev.spring.step02constructor.TapeReader">
		<constructor-arg name="tape" ref="tape"></constructor-arg>
	</bean>

	<bean id="tape" class="dev.spring.step02constructor.Tape">
		<constructor-arg type="String" value="아일랜드"></constructor-arg>
		<constructor-arg type="boolean" value="true"></constructor-arg>
	</bean>
</beans>

2) MyRoom 클래스에서 xml 기반 컨테이너 구성.

=> ApplicationContext context = new ClassPathXmlApplicationContext("constructor-config.xml");

 xml 파일명 설정만 다르게 해주면 된다.

 

그래서 결과 출력문은

- TapeReader(Tape tape) called // TapeReader(Tape tape)이 생성되었을 때.

- TapeReader 입니다.  // TapeReader toString() 메서드 실행

- 아일랜드 정상 동작합니다. // TapeReader test() 메서드 실행

 

> setter주입이 아니므로 setter 출력문이 출력되지 않음.!! 

 

정리하다보니 더 쏙쏙 이해가 된다....! 과정을 이해하자 플로우를 이해하자~!~!

728x90

BELATED ARTICLES

more