티스토리 뷰

Java/Spring

<Spring> @Primary이란?

면목동인간 2023. 10. 8. 22:06

@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 객체가 주입되었다.

 

 


본 포스팅은 “자바 웹 개발 워크북/구멍가게 코딩단 저”를 읽고 학습한 내용을 정리한 것

댓글
최근에 올라온 글
«   2026/03   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함
Total
Today
Yesterday