이번 기록은 Spring Framwork를 사용하면 얼마나 쉽게 Bean을 등록할 수 있는지 정리하겠습니다.
우리는 Spring Framwork의 @Bean이라는 어노테이션을 사용해서 수동으로 객체를 스프링 빈으로 등록하고 사용할 수 있습니다. 하지만 @Bean을 사용한 것 보다 더 쉽게 객체를 등록하고 스프링이 자동으로 객체를 관리해주고 의존성을 주입해 줄 수 있습니다. 바로 알아보겠습니다.
Spring Bean으로 등록하고 싶은 클래스에 @Component를 붙여줍니다.
@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");
}
}
@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();
}
}
@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이 자동으로 객체를 스프링 빈으로 등록하고 관리를 합니다.