Spring Boot3 & Spring Framework 6 강의 :: Section 3. @Component

suragryen·2024년 2월 8일
0

Udemy-Spring

목록 보기
6/25

Java 객체의 생성 및 관리를 위한 Spring Framework 이해하기🧑🏻‍🏫


1. @Component로 연결 해 주기 전의 코드

public class App03GamingSpringBeans {

	 
	@Bean
	public GamingConsole game() {
		var game = new PacmanGame();
		return game;
	}
	
	@Bean
	public GameRunner gameRunner(GamingConsole game) {
		System.out.println("Paramter:" + game);
		var gameRunner = new GameRunner(game);
		return gameRunner;
	}
	
	//PacmanGame에 @Conponent 어노테이션만 추가했을때 에러발생
	//NoSuchBeanDefinitionException
	//Spring이 game을 찾지 못했기 때문에 발생 -> @Component를 찾지 못함  
	//특정 패키지에서 PacmanGame을 검색해야 한다고 Spring프레임워크에게 알려줘야 함!! -> @ComponentScan으로 패키지 위치 알려
	//Spring이 PacmanGame의 인스턴스를 생성하고 이 인스턴스가 이곳에 와이어링 됐음  
	
	*/
	
	public static void main(String[] args) {
		
		//Spring 컨텍스트에서 Bean을 가져와 실행
		
		try(var context = 
				new AnnotationConfigApplicationContext
				(App03GamingSpringBeans.class)){
			context.getBean(GamingConsole.class).up();
			context.getBean(GameRunner.class).run();
		}

	}

}
  • @Bean을 직접 생성해줘야한다

2. GameConsole과 GameRunner와 pacmanGame을 @Component로 연결 해 주기

  1. GameRunner
@Component
public class GameRunner {
		GamingConsole game;
		
		public GameRunner(GamingConsole game) {
			this.game = game;
		}


		public void run() {
			System.out.println("Running game: " + game);
			//System.out 보다 로깅 프레임워크를 사용하는것이 좋다  
			game.up();
			game.down();
			game.left();
			game.right();
			
		}
	
}
  1. pakmanGame
@Component

//어노테이션 기반의 Configuration과 클래스패스 스캐닝을 사용할 때, 자동 감지에 대한 후보로 간주  
//Spring이 우리에게 PacmanGame의 인스턴스를 생성해주는 것 
//GamingConsole로 auto wiring 해준다 

public class PacmanGame implements GamingConsole{

	
	public void up() {
		System.out.println("up!!");
		
	}
	
	
	public void down() {
		System.out.println("Sit down!!");
	}
	
	public void left() {
		System.out.println("Go back!!");
	}
	
	public void right() {
		System.out.println("Shoot a bullet!!");
	}

}

@Component

  • 어노테이션 기반의 Configuration과 클래스패스 스캐닝을 사용할 때, 자동 감지에 대한 후보로 간주
  • Spring이 우리에게 PacmanGame의 인스턴스를 생성해주는 것
  • GamingConsole로 auto wiring 해준다
package com.in28minutes.learnspringframework;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import com.in28minutes.learnspringframework.game.GameRunner;
import com.in28minutes.learnspringframework.game.GamingConsole;
import com.in28minutes.learnspringframework.game.MarioGame;
import com.in28minutes.learnspringframework.game.PacmanGame;
import com.in28minutes.learnspringframework.game.SuperContraGame;

@Configuration
@ComponentScan("com.in28minutes.learnspringframework.game;")
public class App03GamingSpringBeans {

	
	//PacmanGame에 @Conponent 어노테이션만 추가했을때 에러발생
	//NoSuchBeanDefinitionException
	//Spring이 game을 찾지 못했기 때문에 발생 -> @Component를 찾지 못함  
	//특정 패키지에서 PacmanGame을 검색해야 한다고 Spring프레임워크에게 알려줘야 함!! -> @ComponentScan으로 패키지 위치 알려
	//Spring이 PacmanGame의 인스턴스를 생성하고 이 인스턴스가 이곳에 와이어링 됐음  

	
	public static void main(String[] args) {
		
		//Spring 컨텍스트에서 Bean을 가져와 실행
		
		try(var context = 
				new AnnotationConfigApplicationContext
				(App03GamingSpringBeans.class)){
			context.getBean(GamingConsole.class).up();
			context.getBean(GameRunner.class).run();
		}
		
		
//		var game = new PacmanGame();	//1: Object Creation
//		//var game = new MarioGame();
//		//var game = new SuperContraGame(); 
//		var gameRunner = new GameRunner(game); 
//		//2: Object Creation + Wiring of Dependencies
//		// Game is a Dependency of GameRunner 게임을 실행하려면 게임이 있어야 하므로 게임이 의존성이
//			gameRunner.run();

	}

}
- PacmanGame에 @Conponent 어노테이션만 추가했을때 에러발생
- NoSuchBeanDefinitionException
- Spring이 game을 찾지 못했기 때문에 발생 -> @Component를 찾지 못함  
- 특정 패키지에서 PacmanGame을 검색해야 한다고 Spring프레임워크에게 알려줘야 함!! -> @ComponentScan으로 패키지 위치 알려준다 
- Spring이 PacmanGame의 인스턴스를 생성하고 이 인스턴스가 이곳에 와이어링 됐음  



1. 올바른 패키지 스캔
2. 컴포넌트 찾기
3. 인스턴스 생성
4. 자동으로 추가
5. 어플리케이션 작동

```

@Conponent를 다른 클래스에도 적용한다면?

NoUniqueBeanDefinitionExceiption 발생
->유니크한 클래스를 만들어 줘야한다

  1. @Primary
    : 여러 후보가 단일값 의존성을 자동 와이어링할 자격이 있는 경우 Bean에 우선권을 부여한다.
  • @Primary로 우선권을 부여해준다
  • 여러 후보들중에 Spring 프레임 워크에게 MarioGame을 사용하라고 알려줌
@Primary
public class MarioGame implements GamingConsole{

	public void up() {
		System.out.println("Jump");
		}
	
	
	public void down() {
		System.out.println("Go into a hole");
		}
	
	public void left() {
		System.out.println("Go back");
		}
	
	public void right() {
		System.out.println("Accelerate");
		}	
	
}

2.@Qualifier
: 자동 와이어링 시 필드나 매개변수에서 후보 Bean에 대한 한정자(qualifier)로 쓰인다.

  • Spring에서 여러 개의 동일한 타입의 빈이 등록되어 있는 경우, @Qualifier를 사용하여 특정 빈을 명시적으로 선택할 수 있습니다. 이 어노테이션을 사용하면 스프링 컨테이너가 해당 타입의 빈 중에서 지정된 이름 또는 구분자를 사용하여 특정 빈을 주입하게 됩니다.
@Qualifier("SuperContraGameQualifier")
public class SuperContraGame implements GamingConsole{
	
	public void up() {
		System.out.println("up");
		
	}
	
	
	public void down() {
		System.out.println("Sit down");
	}
	
	public void left() {
		System.out.println("Go back");
	}
	
	public void right() {
		System.out.println("Shoot a bullet");
	}

}
@Component
public class GameRunner {
		GamingConsole game;
		
		public GameRunner(@Qualifier("SuperContraGameQualifier") GamingConsole game) {
			this.game = game;
		}


		public void run() {
			System.out.println("Running game: " + game);
			//System.out 보다 로깅 프레임워크를 사용하는것이 좋다  
			game.up();
			game.down();
			game.left();
			game.right();
			
		}
	
}
  • gameRunner에서 생성자 주입을 통해 자동 와이어링 할 수 있다

@Primary 와 @Qualifier 중에서는 @Qualifier이 우선순위이다!

profile
블로그 이사중 ☃︎

0개의 댓글

관련 채용 정보