Programming/Spring

@Component와 @Bean

사랑우주인 2024. 12. 12. 17:27

@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