스프링 데이터 JPA에서의 @Repository

대영·2023년 11월 27일
2

Spring

목록 보기
5/15

🙏내용에 대한 피드백은 언제나 환영입니다!!🙏

결론부터 말하자면, 스프링 데이터 JPA에서는 Repository 인터페이스를 상속하는 인터페이스에서는 자동 빈 등록을 위한 @Repositoy를 사용하지 않는다.

❓JpaRepository 뜯어보기

@NoRepositoryBean
public interface JpaRepository<T, ID> extends ListCrudRepository<T, ID>, ListPagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T>  {}

위 코드는 JpaRepository의 코드이다.
이 코드에서 볼 수 있는 것은 @NoRepositoryBean 어노테이션이다.

❕@NoRepositoryBean 뜯어보기

@NoRepositoryBean에는 다음과 같은 내용이 적혀있다.


Annotation to exclude repository interfaces from being picked up and thus in consequence getting an instance being created.
This will typically be used when providing an extended base interface for all repositories in combination with a custom repository base class to implement methods declared in that intermediate interface. In this case you typically derive your concrete repository interfaces from the intermediate one but don't want to create a Spring bean for the intermediate interface.


Spring Data JPA에서 리포지토리 인터페이스를 스캔하지 않고, 결과적으로 해당 인터페이스에 대한 빈을 생성하지 않도록 제외한다. 이는 주로 모든 리포지토리에 공통으로 적용되는 기본 인터페이스를 제공하고, 해당 중간 인터페이스에서 선언된 메서드를 구현한 사용자 지정 리포지토리 기본 클래스와 함께 사용할 때 유용합니다. 이 경우에는 일반적으로 구체적인 리포지토리 인터페이스를 중간 인터페이스에서 파생시키지만 중간 인터페이스에 대한 Spring 빈을 생성하고 싶지 않을 때 사용됩니다.


즉, 스프링 빈을 생성하지 않는다는 어노테이션이다.

❓왜 사용하지 않는가

그 이유는 스프링 부트에서 디폴트되어 있는 @EnableJpaRepositories 때문이다.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(JpaRepositoriesRegistrar.class)
public @interface EnableJpaRepositories {

@EnableJpaRepositories를 보면 @Import(JpaRepositoriesRegistrar.class)되어 있는 것을 볼 수 있다.
여기에서 실제로 JpaRepository를 상속받은 repository 인터페이스를 빈으로 등록해주는 역활을 한다.

💡결론

스프링 데이터 JPA에서는 Repository 인터페이스를 상속하는 인터페이스에서는 자동 빈 등록을 위한 @Repositoy를 사용하지 않는다!

profile
Better than yesterday.

0개의 댓글