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

2023. 10. 24. 20:00
728x90

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

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

- Tape --> @Value 애너테이션 

- TapeReader --> @Autowired 애너테이션 사용

 

1. Field 기반 주입

1) annotation-config-field.xml 파일 생성

  • 해당 링크에서 xml 엘리먼트 가지고오기
  • Annotation 기반 설정 구성을 하기 위한 엘리먼트를 추가해야 함 : xmlns:context attribute를 추가했기 때문에 애너테이션 작성이 가능함. (xmlns:context="http://www.springframework.org/schema/context")
  • 그 외에도 @Autowired, @Qualifier 등 의존성 주입용 애너테이션 활성화를 위한 엘리먼트임. 
  • <bean> 설정을 XML이 아닌 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"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		https://www.springframework.org/schema/context/spring-context.xsd">

	<context:annotation-config />

	<bean id="tapeReader" class="dev.spring.step01field.TapeReader">
	</bean>

	<bean id="tape" class="dev.spring.step01field.Tape">
	</bean>
</beans>

>> <bean> 태그 내부의 세부설정이 사라짐. 

<context:annotation-config /> 태그 설정.

 

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

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

package dev.spring.step01field;

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

public class MyRoom {

	public static void main(String[] args) {
		
		// 1. XML 파일을 사용하지만 Annotation이 적용되어 보다 간소화된 방식
		// field 기반 주입!!
		ApplicationContext context = new ClassPathXmlApplicationContext("annotation-config-field.xml");
		
		TapeReader reader = context.getBean(TapeReader.class);
		System.out.println(reader);
		reader.test();
	}
}

* Tape ( @Value 애너테이션 사용하여 필드 설정)

package dev.spring.step01field;

import org.springframework.beans.factory.annotation.Value;

public class Tape {
	
	// 필드 기반으로 injection 할 수 있다~ @Value 태그를 통해.. 걍 알고 넘어가기
	@Value("아일랜드")	private String name; 
	@Value("true")  private boolean isWorked; 

	public Tape() {
		super();
		System.out.println("step01field 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() called");
		this.name = name;
	}

	public boolean isWorked() {
		return isWorked;
	}

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

}

* TapeReader (@Autowired 애너테이션 활용하여 의존성을 자동 연결)

autowired태그를 통해 bean에서 알아서 연결해줘라...라고 요청 > 먼저 xml 파일에서 bean 안의 wiring하던 코드를 쓸필요가 없어짐.

package dev.spring.step01field;

import org.springframework.beans.factory.annotation.Autowired;

public class TapeReader {

	// 의존성을 자동으로 연결해주는 옵션.
	@Autowired
	private Tape tape;

	public void test() {

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

	public void setTape(Tape tape) {
		System.out.println("setType(Tape tape) called");
		this.tape = tape;
	}

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

}

출력문 순서 !

- step01field Tape() called  // Tape tape 생성 순간 + 필드에 아일랜드/true 값 들어

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

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

 

이 방식이 field 기반으로 의존성 주입한 것. 필드인 Tape tape에 @Autowired 애너테이션 사용.

 

 

2. Setter 기반 주입

1) annotation-config-setter.xml 파일 생성

이것도 마찬가지로 xml 파일 설정부터 한다. 위와 완전 동일.

 

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

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

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

 

3) @Autowired 애너테이션을 setter에 설정.

field 기반은 필드에 애너테이션을 달았다면 > setter기반은 setTape(Tape tape)에 달아주기만 하면 끝.

package dev.spring.step02setter;

import org.springframework.beans.factory.annotation.Autowired;

public class TapeReader {

	private Tape tape;

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

	@Autowired
	public void setTape(Tape tape) {
		System.out.println("setType(Tape tape) called");
		this.tape = tape;
	}

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

}

출력문 순서 !

 

- step02setter Tape() called  // Tape tape 생성 순간 + 필드에 아일랜드/true 값 들어감.

- setTape(Tape tape) called // TapeReader setTape(Tape tape) 메서드 실행

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

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

 

> 아주 간단하다~ 애너테이션을 어디다 두냐에 따라 달라집니다.

 

3. 생성자 기반 주입

1) annotation-config-constructor.xml 파일 생성

위와 완전 동일.

 

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

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

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

 

3) @Autowired 애너테이션을 생성자에 설정.

필드값을 넣은 생성자를 생성한 후 거기에 애너테이션 달기. 

package dev.spring.step03constructor;

import org.springframework.beans.factory.annotation.Autowired;

public class TapeReader {
	private Tape tape;

	@Autowired
	public TapeReader(Tape tape) {
		this.tape = tape;
	}

	public void test() {
			...
}

출력문 순서 !

 

- step03constructor Tape() called  // Tape tape 생성 순간 + 필드에 아일랜드/true 값 들어감.

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

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

 

 

순서를 따르면서 하나씩 이해하다 보니 정말 쉽게 이해가 된다. 쁠로우의 중요성........ 

이런 게 의존성 주입이구나...

728x90

BELATED ARTICLES

more