Java 객체의 생성 및 관리를 위한 Spring Framework 6

Soo·2024년 3월 5일

이번 기록은 Spring Framwork를 사용하면 얼마나 쉽게 Bean을 등록할 수 있는지 정리하겠습니다.

우리는 Spring Framwork의 @Bean이라는 어노테이션을 사용해서 수동으로 객체를 스프링 빈으로 등록하고 사용할 수 있습니다. 하지만 @Bean을 사용한 것 보다 더 쉽게 객체를 등록하고 스프링이 자동으로 객체를 관리해주고 의존성을 주입해 줄 수 있습니다. 바로 알아보겠습니다.

@Component - 클래스를 Spring Bean으로 선언하는 데 사용되는 어노테이션입니다. Spring의 ApplicationContext가 해당 클래스를 Bean으로 자동으로 등록하고, 필요에 따라 의존성 주입을 수행할 수 있습니다.

사용법

Spring Bean으로 등록하고 싶은 클래스에 @Component를 붙여줍니다.

PacmanGame 스프링 빈으로 등록

@Component
public class PacmanGame implements GamingConsole {
		public void up(){
			System.out.println("up");
		}
			public void down(){
			System.out.println("down");
		}
		public void left(){
			System.out.println("left");
		}
		public void right(){
			System.out.println("right");
		}
}

GameRunner 스프링 빈으로 등록

@Component
public class GameRunner {

		private GamingConsole game;
		
		public GameRunner(GamingConsole game) {
				this.game = game;
		}
		
		public void run() {
				System.out.println("Running game: " + game);
				game.up();
				game.down();
				game.left();
				game.right();
		}
}

등록한 PacmanGame Bean 사용하기

@ComponentScan을 사용해서 @Component로 등록된 Bean을 조회한다.

만약 AppGamingSpringBeans와 pacmanGame을 서로 다른 패키지에 만들었을 경우 @ComponentScan에 패키지를 명시해줘야 한다.

@Configuration
@ComponentScan("com.in28minutes.learnspringframework.game")
public class AppGameingSpringBeans{
		public static void main(String[] args) {
				
				try(var context = new AnnotationConfigApplicationContext(AppGameingSpringBeans.class)) {
						context.getBean(GamingConsole.class).up();

						context.getBean(GameRunner.class).run();
				}
		}
}

실행

up
Running game: com.in28minutes.learnspringframework.game.PacmanGame@1e04fa0a
up
down
left
right

사용자가 별도의 Configuration 파일을 만들고 @Bean 어노테이션을 사용해서 코드를 등록하는 대신 @Component를 사용하면 Spring이 자동으로 객체를 스프링 빈으로 등록하고 관리를 합니다.

0개의 댓글