티스토리 뷰
@Primary이란?
@Primary 어노테이션은 예를 들어 클래스 A에 인터페이스 B를 선언했는데 인터페이스를 구현한 객체 2개가 존재할 경우 스프링은 어느 객체를 주입해야 하는지 알 수 없게 되는데 주입할 객체에 어노테이션을 지정하면 해당 객체가 주입이 된다.
@Primary 예제
인터페이스
public interface SampleDAO {
}
인터페이스 구현 객체
@Repository
public class SampleDAOImpl implements SampleDAO {
}
@Repository
public class EventSampleDAOImpl implements SampleDAO {
}
의존 객체
@Service
@ToString
@RequiredArgsConstructor
public class SampleService {
private final SampleDAO sampleDAO;
}
테스트 코드
@Log4j2
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/root-context.xml")
public class SampleTests {
@Autowired
private SampleService sampleService;
@Test
public void testService() {
log.info(sampleService);
}
}
SampleDAO를 구현한 2개의 객체를 실행하면 아래와 같은 메세지가 나온다. SampleDAO 타입의 객체가 2개가 발견되었다는 것이다.

해결 방법
해결 방법은 주입할 객체에 @Primary 어노테이션을 붙이면 된다.
@Repository
@Primary
public class EventSampleDAOImpl implements SampleDAO {
}
테스트 코드를 실행 후 로그를 보면 아래와 같다. @Primary 어노테이션이 붙은 EventSampleDAOImpl 객체가 주입되었다.

본 포스팅은 “자바 웹 개발 워크북/구멍가게 코딩단 저”를 읽고 학습한 내용을 정리한 것
'Java > Spring' 카테고리의 다른 글
| <Spring> 트랜잭션 프록시 내부 호출시 문제점 (0) | 2024.07.29 |
|---|---|
| <Spring> @SessionAttribute 이란? (0) | 2024.07.25 |
| <Spring> List, Map으로 빈 주입 받기 (0) | 2024.07.19 |
| <Spring> @RequiredArgsConstructor과 의존성 주입 (0) | 2023.10.09 |
| <Spring> @Qualifier이란? (1) | 2023.10.09 |
댓글
