Spring

@Component, @Bean 어노테이션

Karla Ko 2023. 9. 14. 02:16
728x90

@Component

  • 클래스를 Spring에서 알아서 관리해주는 자바 빈으로 표시하는 데 사용
  • Spring이 자동으로 클래스의 인스턴스를 생성하고 종속성을 포함하여 각종 lifecycle 관리
@Component
public class MyComponent {
  // ...
}

 

@Autowired

  • ApplicationContext에 종속성을 주입
  • Spring에서 필요한 종속성의 인스턴스를 자동으로 주입
@Component
public class MyComponent {
  private MyService myService;

  @Autowired
  public MyComponent(MyService myService) {
    this.myService = myService;
  }

  // ...
}

 

@Service, @Controller, @Repository

  • @Component의 메타 어노테이션
  • @Component의 모든 기능을 상속하고 일부 추가적인 기능들이 들어간 어노테이션
  •  Spring이 자동으로 자바 빈을 찾아서 관리해줄 뿐만 아니라 이것이 Service인지 Controller인지에 따라 추가적인 기능 제공

 

@Bean

  • Spring에서 관리할 Bean을 명시적으로 선언하는 데 사용
  • @Component와 달리 @Bean은 개발자가 Bean의 생성 및 구성을 사용자 정의할 수 있도록 함
@Configuration
public class WebConfig implements WebMvcConfigurer {
  
  @Bean
  public LocaleResolver localeResolver() {
    SessionLocaleResolver resolver = new SessionLocaleResolver();
    resolver.setDefaultLocale(Locale.US);
    return resolver;
  }
  // ...
}

 

@Configuration

  • @Configuration 어노테이션은 해당 클래스에서 1개 이상의 Bean을 생성하고 있음을 명시
  • 그러므로 @Bean 어노테이션을 사용하는 클래스는 반드시 @Configuration과 함께 사용되어야 함

 

 

728x90