Spring Framework를 사용하다 보면 자주 마주치게 되는 두 가지 어노테이션이 있습니다. 바로 @Bean
과 @Component
입니다. 둘 다 Spring IoC 컨테이너에 빈(Bean)을 등록하는 방법이지만, 사용 목적과 방식에는 중요한 차이가 있습니다. 이번 글에서는 이 두 어노테이션의 차이점과 각각의 사용 사례에 대해 자세히 알아보겠습니다.
@Controller
, @Service
, @Repository
등은 모두 @Component
를 포함하고 있는 특수화된 어노테이션입니다@Component
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User findUser(Long id) {
return userRepository.findById(id);
}
}
@Configuration
@ComponentScan(basePackages = "com.example.project")
public class AppConfig {
// 설정 내용
}
@Configuration
클래스 내부에서 사용됩니다@Configuration
public class DatabaseConfig {
@Bean
public DataSource dataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
dataSource.setUsername("user");
dataSource.setPassword("password");
dataSource.setMaximumPoolSize(10);
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
@Service // @Component의 특수화된 어노테이션
public class OrderService {
private final OrderRepository orderRepository;
private final PaymentService paymentService;
public OrderService(OrderRepository orderRepository, PaymentService paymentService) {
this.orderRepository = orderRepository;
this.paymentService = paymentService;
}
public void processOrder(Order order) {
// 주문 처리 로직
}
}
@Repository // @Component의 특수화된 어노테이션
public class JpaOrderRepository implements OrderRepository {
private final EntityManager em;
public JpaOrderRepository(EntityManager em) {
this.em = em;
}
@Override
public Order save(Order order) {
em.persist(order);
return order;
}
}
@Configuration
public class WebConfig {
// RestTemplate 빈 등록
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper;
}
// webClient 빈 등록
@Bean
public WebClient webClient() {
return WebClient.builder().build();
}
}
@Configuration
public class CacheConfig {
@Bean
public Cache userCache() {
return new ConcurrentMapCache("userCache");
}
@Bean
public Cache productCache() {
return new ConcurrentMapCache("productCache");
}
}
선언 위치
사용 대상
등록 방식
제어 수준
@Component
는 우리가 작성한 코드를 스프링이 관리하도록 할 때 사용하고, @Bean
은 외부 라이브러리나 상세한 설정이 필요한 객체를 스프링이 관리하도록 할 때 사용합니다. 도움이 되셨으면 좋겠습니다. 물론 저에게도요.