문제상황:
Spring Boot 프로젝트에서 자주 발생하는 에러 중 하나는 "No qualifying bean of type" 에러입니다. 이 예시에서는 실무에서 사용될 수 있는 코드를 사용하여 이 에러를 재현하고 해결해보겠습니다.
아래는 에러가 발생한 코드와 이에 대한 설명입니다.
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
//...
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
이 코드에서 발생한 에러 로그는 다음과 같습니다.
No qualifying bean of type 'com.example.demo.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
해결방법:
에러가 수정된 코드와 수정된 부분에 대한 주석을 확인해봅시다.
// @Configuration 어노테이션 추가
@Configuration
public class RepositoryConfiguration {
// UserRepository 빈 정의 추가
@Bean
public UserRepository userRepository() {
return new UserRepositoryImpl();
}
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
//...
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
원인분석:
이 에러는 Spring Boot가 UserRepository 타입의 빈을 찾지 못하여 발생합니다. UserRepository 인터페이스는 JpaRepository를 확장하고 있기 때문에, Spring Boot는 자동으로 구현체를 생성하고 빈으로 등록해야 합니다. 그러나 이 경우에는 빈을 찾지 못했습니다.
이 문제의 해결 방법은 다음과 같습니다.
- @Configuration 어노테이션을 사용하여 빈 설정 클래스를 생성합니다.
- 해당 클래스에서 UserRepository 타입의 빈을 정의하고, 구현체를 반환하는 메서드를 추가합니다.
이렇게 하면 Spring Boot는 UserRepository 타입의 빈을 찾을 수 있으며, UserService에 올바르게 주입할 수 있습니다.
참고링크:
Spring Boot 공식문서 - No qualifying bean of type 에러
[Core Technologies
In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do
docs.spring.io](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-collaborators)