@Component와 @Bean

2024. 12. 12. 17:27·Programming/Spring

@Component와 @Bean의 차이

특징 @Component @Bean
사용 위치 클래스 레벨 메서드 레벨
자동 감지 스프링의 컴포넌트 스캔으로 자동 감지 가능 스프링이 명시적으로 메서드를 호출하여 빈 생성
소스 코드 의존성 클래스의 소스 코드가 수정 가능해야 사용 가능 제3자 라이브러리 클래스에도 적용 가능
유연성 간결하지만 인스턴스 생성 로직에 대한 제어 제한 로직 추가를 통해 다양한 조건에 따른 빈 생성 가능

@Component는 수정 가능한 클래스에만 적용될 수 있다는 점이 의문이 들었지만, 외부 라이브러리 클래스는 코드 수정이 불가능하므로 @Component 애노테이션을 붙일 수 없다는 점을 생각하면 당연하다. 따라서, 외부 라이브러 클래스는 @Bean을 통해 빈 생성이 가능하다.

BeanExample might represent a local class, or it might be an external class. It doesn’t matter because we need to return an instance of it.
We can then write a test that verifies Spring did pick up the bean:
@Bean
public BeanExample beanExample() {
    return new BeanExample();
}

 

@Component의 Sterotype 애노테이션

@Component의 스테레오타입(stereotype) 애노테이션은 스프링에서 특정 목적에 따라 사용되는 애노테이션들로, @Component를 확장한 애노테이션들이다. @Service, @Repository, @Controller 등이 있다.

번외

번외로, @Autowired와 가끔 혼동하는데, @Autowired는 의존성 주입을 위한 것이며, 직접적으로 객체를 생성하지 않는다. Spring 컨테이너에게 해당 타입의 빈을 찾아 주입하라고 지시하는 역할을 한다.

참고

https://www.baeldung.com/spring-component-annotation

'Programming > Spring' 카테고리의 다른 글

Resource 추상화  (0) 2024.12.13
ApplicationEventPublisher  (0) 2024.12.13
Autowired  (0) 2024.12.11
ApplicationContext 2가지 빈 설정 방식  (0) 2024.12.11
RequestBody 자바 객체 매핑  (0) 2024.12.11
'Programming/Spring' 카테고리의 다른 글
  • Resource 추상화
  • ApplicationEventPublisher
  • Autowired
  • ApplicationContext 2가지 빈 설정 방식
사랑우주인
사랑우주인
  • 사랑우주인
    lovelyAlien
    사랑우주인
  • 전체
    오늘
    어제
  • 글쓰기
    관리
    • 분류 전체보기 (209)
      • Programming (4)
        • Spring (28)
        • Java (46)
        • JPA (2)
        • 디자인 패턴 (5)
        • 개발&아키텍처 (0)
      • Network (14)
      • OS (19)
      • Database (1)
      • Kubernetes (0)
      • Kafka (2)
      • Algorithm (49)
        • BaekJoon (1)
        • Programmers (19)
        • Algorithm (5)
        • Socar (2)
        • LeetCode (19)
      • Interview (2)
      • Issues (2)
      • DotJoin (1)
      • Git (4)
      • 독서 (3)
      • 끄적끄적 (1)
      • 외부활동 (26)
        • 항해플러스 (2)
        • JSCODE 네트워크 (19)
        • JSCODE 자바 (5)
      • SQL (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • GitHub
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    디자인 패턴
    socar
    rotting oranges
    BFS
    추상화 클래스
    @JsonNaming
    Reorder List
    wildcards
    fcfs
    pacific atlantic water flow
    Thread
    트랜잭션
    JSCode
    Process
    Oauth2
    제네릭
    AuthenticationSuccessHandler
    LinkedList
    algorithm
    운영체제
    clone graph
    minimum number of arrows to burst balloons
    준영속 엔티티
    runner 기법
    lower bounded wildcards
    RR
    OS
    Climbing Stairs
    @JsonProperty
    Generic
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.1
사랑우주인
@Component와 @Bean
상단으로

티스토리툴바