JAVA/오류해결

[Spring Boot][오류해결] Parameter 0 of constructor in ~~ required a single bean, but 2 were found

gakko 2022. 2. 13. 13:00

 

Description:

Parameter 0 of constructor in com.bigbell.springboot.cruddemo.service.EmployeeServiceImpl 
required a single bean, but 2 were found:
- employeeDAOHibernateImpl: defined in file [D:\bigbell\Spring-Boot\22-jpa-crud-
demo\target\classes\com\bigbell\springboot\cruddemo\dao\EmployeeDAOHibernateImpl.class]
- employeeDAOJpaImpl: defined in file [D:\bigbell\Spring-Boot\22-jpa-crud-
demo\target\classes\com\bigbell\springboot\cruddemo\dao\EmployeeDAOJpaImpl.class]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using 
@Qualifier to identify the bean that should be consumed

 

스프링부트를 사용할 때 발생하는 에러이다.

APPLICATION FAILED TO START 에러가 발생하면 위와 같이 자세한 설명이 나오는데

문제는 다음과 같다.

특정 인터페이스를 상속한 클래스 파일이 여러 개일 때

의존성 주입을 위해 @Primary, @Qualifier 어노테이션을 사용해야하는데

@Autowired를 적었기 때문에 여러 개의 클래스가 충돌하여 에러가 발생하는 것이다.

 

 

Action에 나온 것을 그대로 적용해주면 해결된다.

대충 해석해보자면, @Primary 어노테이션을 통해 우선순위를 정해주거나

@Qualifier 어노테이션으로 빈 하나를 설정해주라는 거 같다.

 

 

 

예시1


문제상황  - MyInterface를 상속한 클래스가 여러 개일때, 멤버변수에 의존성 주입

@Autowired
private MyInterface myInterface;

 

해결

@Qualifier("클래스명")
private MyInterface myInterface;

 

 

 

예시2


문제상황 - MyInterface를 상속한 클래스가 여러 개일때, 생성자 인자에 의존성 주입

private MyInterface myInterface;

@Autowired
public 생성자(MyInterface myInterface) {
    this.myInterface = myInterface;
}

 

해결

private MyInterface myInterface;

@Autowired
public 생성자(@Qualifier("클래스명") MyInterface myInterface) {
    this.myInterface = myInterface;
}