프로그래밍 공부
@Component와 @Bean의 차이 본문
@Component와 @Bean은 스프링에서 빈(Bean)을 등록하는 방법이지만, 사용 방식과 목적이 다르다.
1. @Component
✅ 클래스 수준에서 사용하며, 자동으로 빈을 등록할 때 활용
✅ @ComponentScan을 통해 해당 패키지 내의 클래스를 자동 감지하여 빈으로 등록
📌 사용 예시
import org.springframework.stereotype.Component;
@Component // MyService가 자동으로 빈으로 등록됨
public class MyService {
public void sayHello() {
System.out.println("Hello from MyService!");
}
}
📌 @ComponentScan 설정
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.example.service") // 해당 패키지 내 @Component를 스캔하여 빈 등록
public class AppConfig {
}
💡 결과: MyService가 자동으로 빈으로 등록됨.
2. @Bean
✅ 메서드 수준에서 사용하며, 직접 객체를 생성하여 빈으로 등록
✅ @Configuration 클래스 내에서 사용됨
📌 사용 예시
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean // 직접 객체를 생성하여 빈으로 등록
public MyService myService() {
return new MyService();
}
}
💡 결과: myService라는 이름의 빈이 등록됨.
3. @Component vs @Bean 차이점
비교 항목 @Component @Bean
사용 위치 | 클래스에 사용 (@Component, @Service, @Repository, @Controller) | @Configuration 클래스 내부 메서드에 사용 |
빈 등록 방식 | 자동 감지 (@ComponentScan 필요) | 개발자가 직접 객체를 생성하여 등록 |
사용 목적 | 일반적인 서비스, DAO, 컨트롤러 클래스 등록 | 외부 라이브러리 또는 특정한 객체를 빈으로 등록할 때 사용 |
객체 관리 | 스프링이 자동 생성 | 개발자가 직접 객체를 생성 |
4. 언제 @Component를 쓰고, 언제 @Bean을 써야 할까?
✔ @Component를 사용해야 하는 경우
- 직접 구현한 클래스(예: 서비스, 컨트롤러, DAO 등)를 빈으로 등록할 때
- @ComponentScan을 사용하여 자동 감지를 활용할 때
✔ @Bean을 사용해야 하는 경우
- 외부 라이브러리의 클래스를 빈으로 등록할 때
- 인스턴스 생성 과정이 복잡하거나, 특정 설정이 필요할 때
- 인터페이스의 구현체를 동적으로 변경해야 할 때
5. @Component와 @Bean을 같이 쓰면?
만약 같은 타입의 빈을 @Component와 @Bean으로 동시에 등록하면 중복 문제가 발생할 수 있다.
이 경우 @Primary 또는 @Qualifier를 활용하여 해결할 수 있다.
📌 중복 문제 해결
@Bean
@Primary // 기본 빈으로 지정
public MyService myService1() {
return new MyService();
}
@Autowired
@Qualifier("myService2") // 특정 빈을 지정하여 사용
private MyService myService;
📌 결론
✅ 자동 빈 등록이 가능하면 @Component 사용
✅ 외부 라이브러리 또는 복잡한 빈 생성이 필요하면 @Bean 사용
'Programming > Spring' 카테고리의 다른 글
Java Bean(EJB), POJO, Spring Bean (0) | 2025.02.06 |
---|---|
Spring Container (0) | 2025.02.06 |
Class 형태로 Bean 접근 방법 (0) | 2025.02.06 |
Java Config 사용 Bean 설정 (0) | 2025.02.06 |
Spring 및 Bean 설정 (0) | 2025.02.06 |
Comments