[Spring Boot] BeanCreationException 오류 해결 방법
📌 [Spring Boot] BeanCreationException 오류 해결 방법
📌 BeanCreationException이란?
BeanCreationException은 Spring에서 빈(Bean)을 생성하는 과정에서 문제가 발생할 때 발생하는 예외입니다.
대부분 의존성 주입, 빈 설정 오류, 순환 참조 등의 이유로 발생합니다.
📌 BeanCreationException이 발생하는 주요 원인과 해결 방법
1️⃣ @Component, @Service, @Repository 등의 빈 등록 누락
설명: Spring에서는 @Component
, @Service
, @Repository
또는 @Bean
을 사용하여 빈을 등록해야 합니다.
이러한 애너테이션이 누락되면 Spring이 빈을 찾을 수 없고, BeanCreationException
이 발생합니다.
오류 발생 예제:
public class MyService {
public String getService() {
return "Hello";
}
}
@Autowired
private MyService myService; // BeanCreationException 발생
해결 방법: 해당 클래스에 @Service
애너테이션을 추가하거나 @ComponentScan
을 설정하여 패키지를 스캔하도록 해야 합니다.
@Service
public class MyService {
public String getService() {
return "Hello";
}
}
2️⃣ @Autowired를 사용할 때 빈이 존재하지 않는 경우
설명: @Autowired를 사용하여 빈을 주입할 때, 해당 빈이 존재하지 않으면 BeanCreationException
이 발생할 수 있습니다.
오류 발생 예제:
@Service
public class OrderService {
@Autowired
private PaymentService paymentService; // PaymentService 빈이 존재하지 않으면 오류 발생
}
해결 방법: @Autowired 대신 생성자 주입을 사용하고, 인터페이스 기반의 빈 주입을 확인해야 합니다.
@Service
public class OrderService {
private final PaymentService paymentService;
@Autowired
public OrderService(PaymentService paymentService) {
this.paymentService = paymentService;
}
}
3️⃣ 순환 참조(Circular Dependency)로 인한 예외
설명: A가 B를 참조하고, B가 다시 A를 참조하는 경우 발생하는 문제입니다.
오류 발생 예제:
@Service
public class AService {
@Autowired
private BService bService;
}
@Service
public class BService {
@Autowired
private AService aService; // 순환 참조 발생
}
해결 방법: 순환 참조 문제를 해결하기 위해 @Lazy
애너테이션을 사용하거나, 생성자 주입 방식으로 변경해야 합니다.
@Service
public class AService {
private final BService bService;
@Autowired
public AService(@Lazy BService bService) {
this.bService = bService;
}
}
4️⃣ 빈이 여러 개 존재할 때 발생하는 충돌
설명: 같은 타입의 빈이 여러 개 존재할 경우, Spring이 어떤 빈을 주입해야 할지 몰라 BeanCreationException
이 발생할 수 있습니다.
오류 발생 예제:
@Service
public class CreditCardPaymentService implements PaymentService { ... }
@Service
public class PayPalPaymentService implements PaymentService { ... }
@Autowired
private PaymentService paymentService; // 어느 빈을 주입해야 할지 모름 -> 오류 발생
해결 방법: @Qualifier 또는 @Primary 애너테이션을 사용하여 명확하게 지정해야 합니다.
@Service
@Primary
public class CreditCardPaymentService implements PaymentService { ... }
또는,
@Autowired
@Qualifier("creditCardPaymentService")
private PaymentService paymentService;
📌 BeanCreationException 예방법 요약
- ✅ @Component, @Service, @Repository, @Bean 애너테이션 확인
- ✅ @Autowired 사용 시, 빈이 존재하는지 확인
- ✅ 순환 참조 발생 여부 확인 후 @Lazy 사용
- ✅ 빈이 여러 개일 경우 @Qualifier 또는 @Primary로 명시적 지정
🔍 결론
BeanCreationException은 Spring Boot에서 **빈을 찾을 수 없거나, 충돌하거나, 순환 참조가 발생할 때** 발생하는 오류입니다.
위 해결 방법을 적용하면 **오류를 방지하고 원활한 애플리케이션 구동**이 가능합니다! 🚀