[Spring] JpaRepository<Entity,ID> 빈 등록 원리 ,@NoRepositoryBean,SpringData 구조 및 JpaRepository 원리

hyewon jeong·2023년 2월 3일
0

Spring

목록 보기
32/59

본글을 학습을 위해 정리한것으로 혹시 틀린곳이나 수정할 부분이 있으면 말씀해주시면 감사하겠습니다.


  • Repository : 특별한 기능을 제공하는 인터페이스가 아닌 마크 인터페이스입니다. 이 인터페이스가 Repository 용도로 사용될 것이라는 것을 알리는 용도로 쓰이죠.

@NoRepositoryBean 어노테이션

  • Repository ~ JpaRepository 까지는 @NoRepositoryBean 이 붙어있는 인터페이스

    번역기를 통해...

이는 일반적으로 모든 리포지토리에 대해 사용자 지정 리포지토리 기본 클래스와 함께 확장 인터페이스를 제공하여 해당 중간 인터페이스에 선언된 메서드를 구현할 때 사용됩니다.
이 경우 일반적으로 중간 저장소 인터페이스에서 구체적인 저장소 인터페이스를 추출하지만 중간 인터페이스에 대한 스프링 빈(Spring bean)을 생성하려고 하지 않습니다.

한마디로 !

이 인터페이스가 Repository 용도로서 사용되는 것이 아닌 단지 Repository의 메서드를 정의하는 인터페이스라는 정보를 부여합니다.(기능확장만 해줌)

Repository 인터페이스를 상속받았기 때문에 Spring Data Jpa 또는 다른 저장소용 Repository가 실제 빈을 만들지 않도록 사용.
실제 사용되는 Repository가 아님은 표시함.

JpaRepository<Entity,ID> 빈 등록 원리

JpaRepository<Entity,ID>

  • @Repository없어도 빈으로 등록되어 사용된다. 어떻게???
  1. JpaRepository<Entity,ID> 붙이면 알맞은 프로그래밍 된 SimpleJpaReository 구현체 빈이 자동 등록된다.

  2. 그 이유는
    @SpringBootApplication 을 통해 자동으로 붙여지는
    @EnableJpaRepositories 의 JpaRepositoriesRegistrar 를 통해서 등록된다.

  3. JpaRepositoriesRegistrar 는 ImportBeanDefinitionRegistrar 의 구현체이다

  • ImportBeanDefinitionRegistrar
    :빈을 프로그래밍을 통해 등록할 수 있게 해준다.
    : jpaRepository를 상속받은 모든 인터페이스를 찾아서 빈으로 등록해준다.
  1. ImportBeanDefinitionRegistrar를 상속받으면 상속받은 구현체가 있을때 스프링에서
    이것의 메서드인 resigterBeanDefinitions를 실행시키도록 해줘서 실제 빈을 레지스트에 등록할수 있도록 프로그래밍 된다.

스프링 데이터 리포지터리 인터페이스 정의하기( Spring Data Repository Interface )

| 리포지터리 인터페이스 예제 (@NoRepositoryBean)
소스 코드

@NoRepositoryBean
public interface MyRepository<T, ID extends Serializable> extends Repository<T, ID> {

    <E extends T> E save(E entity);

    List<T> findAll();

    long count();
}

Repository 인터페이스를 상속받아 MyRepository를 정의한 예제입니다. Repository는 특별한 기능을 제공하는 인터페이스가 아닌 마크 인터페이스입니다. 이 인터페이스가 Repository 용도로 사용될 것이라는 것을 알리는 용도로 쓰이죠.

@NoRepositoryBean 어노테이션은 이 인터페이스가 Repository 용도로서 사용되는 것이 아닌 단지 Repository의 메서드를 정의하는 인터페이스라는 정보를 부여합니다.

위 예제와 마찬가지로 save, findAll 같은 메서드를 정의하면 이 메서드를 통하여 엔티티와 테이블 간에 상호작용이 일어나게 됩니다.

public interface CommentRepository extends MyRepository<Comment, Long>{

    Comment save(Comment comment);

    List<Comment> findAll();
}

MyRepository 인터페이스를 상속받아 제너릭으로 정의된 인수 부분을 구체적인 엔티티와 타입명으로 정의합니다. 이 Repository 인터페이스는 Repository 용도로 쓰이는 인터페이스이며 이것을 통해 DB에 대한 작업을 소스 코드 상에서 진행할 수 있게됩니다.

https://freedeveloper.tistory.com/141
https://engkimbs.tistory.com/823

profile
개발자꿈나무

0개의 댓글