반응형

컴포넌트 스캔과 의존관계 자동 주입 시작하기

 

AS-IS

자바 코드의 @Bean이나 XML의 <bean> 등을 통해서 설정 정보에 직접 등록할 스프링 빈을 나열

(반복되는 코드 작성, 누락 가능성, 설정 정보도 커짐)

 

TO-BE

스프링은 설정 정보가 없어도 자동으로 스프링 빈을 등록하는 컴포넌트 스캔 기능 활용

의존관계도 자동으로 주입하는 @Autowired 활용

 

AutoAppConfig.java

package hello.core;

import hello.core.member.MemberRepository;
import hello.core.member.MemoryMemberRepositroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;

@Configuration
@ComponentScan
public class AutoAppConfig {

    @Bean(name = "memoryMemberRepositroy")
    MemberRepository memberRepository() {
        return new MemoryMemberRepositroy();
    }
}
더보기

강의 내에서는 기존 AppConfig.java 코드를 유지하지 위해서 필터로 제외시킴

@ComponentScan(
        excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class)
)

 

컴포넌트 스캔은 이름 그대로 @Component 애노테이션이 붙은 클래스를 스캔해서 스프링 빈으로 등록

참고: @Configuration 이 컴포넌트 스캔의 대상이 된 이유도 @Configuration 소스코드를 열어보면 @Component 애노테이션이 붙어있기 때문이다.

 

  • MemoryMemberRepository @Component 추가
  • RateDiscountPolicy @Component 추가
  • MemberServiceImpl @Component, @Autowired 추가
  • OrderServiceImpl @Component, @Autowired 추가
@Component
public class OrderServiceimpl implements OrderService{
    private final MemberRepository memberRepository;
    private final DiscountPolicy discountPolicy;

    @Autowired
    public OrderServiceimpl(MemberRepository memberRepository, DiscountPolicy discountPolicy) {
        this.memberRepository = memberRepository;
        this.discountPolicy = discountPolicy;
    }
}

*@Autowired 를 사용하면 생성자에서 여러 의존관계도 한번에 주입받을 수 있다.

 

TEST 결과

> output

18:27:30.642 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [C:\spring-inflearn\core\out\production\classes\hello\core\discount\RateDiscountPolicy.class]
18:27:30.645 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [C:\spring-inflearn\core\out\production\classes\hello\core\member\MemebrServiceImpl.class]
18:27:30.645 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [C:\spring-inflearn\core\out\production\classes\hello\core\member\MemoryMemberRepositroy.class]
18:27:30.646 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [C:\spring-inflearn\core\out\production\classes\hello\core\order\OrderServiceimpl.class]

 

컴포넌트 스캔 및 자동 의존관계 주입 동작 과정

 

1. @ComponentScan

  • @ComponentScan 은 @Component 가 붙은 모든 클래스를 스프링 빈으로 등록한다.
  • 이때 스프링 빈의 기본 이름은 클래스명을 사용하되 맨 앞글자만 소문자를 사용한다.
    빈 이름 기본 전략: MemberServiceImpl 클래스 memberServiceImpl
    빈 이름 직접 지정: 만약 스프링 빈의 이름을 직접 지정하고 싶으면 @Component("memberService2") 이런식으로 이름을 부여하면 된다.

2. @Autowired 의존관계 자동 주입

  • 설정정보를 작성하지 않기 때문에 Autowired로 생성자를 주입해줌(타입을 통하여)
  • getBean(MemberRepository.class) 와 동일
public class MemebrServiceImpl implements MemberService{

    private final MemberRepository memberRepository;

    @Autowired  //ac.getBen(MemberRepository.class) 와 같은 동작함
    public MemebrServiceImpl(MemberRepository memberRepository) {
        this.memberRepository = memberRepository;
    }
}
  • 생성자에 파라미터가 많아도 다 찾아서 자동으로 주입한다.

탐색 위치와 기본 스캔 대상

@Configuration
@ComponentScan(
        basePackages = "hello.core.member",
        basePackageClasses = AutoAppConfig.class,
        excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class)
)
public class AutoAppConfig {
}
  • basePackages : 라이브러리까지 싹다 탐색하기 때문에 비효율, 탐색하고 싶은 것만 탐색할 수 있음
  • AutoAppConfing의 패키지를 탐색
  • Default 값은 @ComponentScan 이 붙은 설정 정보 클래스의 패키지가 시작 위치가 된다.

스프링부트를 쓰면 @ComponentScan 을 쓸 필요도 없다. @SpringBootApplication 에서 이미 들어가 있기 때문

패키지 위치를 지정하지 않고, 설정 정보 클래스의 위치를 프로젝트 최상단에 두는 것을 권장한다.

컴포넌트 스캔 기본 대상

 

컴포넌트 스캔은 @Component 뿐만 아니라 다음과 내용도 추가로 대상에 포함한다. + 부가기능 수행

  • @Component : 컴포넌트 스캔에서 사용
  • @Controlller : 스프링 MVC 컨트롤러에서 사용 및 인식
  • @Service : 스프링 비즈니스 로직에서 사용 + 사실 @Service 는 특별한 처리를 하지 않는다. 대신 개발자들이 핵심 비즈니스 로직이 여기에 있겠구나 라고 비즈니스 계층을 인식하는데 도움이 된다.
  • @Repository : 스프링 데이터 접근 계층에서 사용 및 인식하고, 데이터 계층의 예외를 스프링 예외로 변환해준다. (예를들어 DB가 바뀌면 예외가 그에 따라 바뀌면 서비스 계층도 흔들려서 스프링이 막기를 위해 예외를 추상화해서 반환을 해준다. 이해가 안되면 데이터접근 강의를 보거라)
  • @Configuration : 스프링 설정 정보에서 사용 및 인식하고, 스프링 빈이 싱글톤을 유지하도록 추가 처리를 한다.
@Component
public @interface Controller {
}

@Component
public @interface Service {
}

@Component
public @interface Configuration {
}
참고: 사실 애노테이션에는 상속관계라는 것이 없다. 그래서 이렇게 애노테이션이 특정 애노테이션을 들고
있는 것을 인식할 수 있는 것은 자바 언어가 지원하는 기능은 아니고, 스프링이 지원하는 기능이다.
참고: useDefaultFilters 옵션은 기본으로 켜져있는데, 이 옵션을 끄면 기본 스캔 대상들이 제외된다. 그냥 이런 옵션이 있구나 정도 알고 넘어가자.

필터

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyIncludeComponent {
}

FilterType 옵션

  • ANNOTATION: 기본값, 애노테이션을 인식해서 동작한다. ex) org.example.SomeAnnotation
  • ASSIGNABLE_TYPE: 지정한 타입과 자식 타입을 인식해서 동작한다. ex) org.example.SomeClass
    • Class를 직접 지정해줄 수 있음
  • ASPECTJ: AspectJ 패턴 사용 ex) org.example..Service+
  • REGEX: 정규 표현식 ex) org\.example\.Default.
  • CUSTOM: TypeFilter 이라는 인터페이스를 구현해서 처리 ex) org.example.MyTypeFilter

*ASSIGNABLE_TYPE 간혹 사용하고 Annotation이 이미 구동되기 때문에 굳이 includeFilters 를 사용할 일은 거의 없다. excludeFilters는 여러가지 이유로 간혹 사용할 때가 있지만 많지는 않다.

 

@ComponentScan(
    includeFilters = @Filter(type = FilterType.ANNOTATION, classes =
    MyIncludeComponent.class),
    excludeFilters = @Filter(type = FilterType.ANNOTATION, classes =
    MyExcludeComponent.class)
)
  • includeFilters : 컴포넌트 스캔 대상을 추가로 지정한다.
  • excludeFilters : 컴포넌트 스캔에서 제외할 대상을 지정한다.
참고: @Component 면 충분하기 때문에, includeFilters 를 사용할 일은 거의 없다. excludeFilters 는 여러가지 이유로 간혹 사용할 때가 있지만 많지는 않다.

 

BeanA도 빼고 싶으면 다음과 같이 추가

@ComponentScan(
    includeFilters = {
    	@Filter(type = FilterType.ANNOTATION, classes =
    MyIncludeComponent.class),
    },
    excludeFilters = {
        @Filter(type = FilterType.ANNOTATION, classes =
        MyExcludeComponent.class),
        @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = BeanA.class)
    }
)

 

 


중복 등록과 충돌

  • 자동 빈 등록 vs 자동 빈 등록 : 컴포넌트 스캔에 의해 자동으로 스프링 빈이 등록되는데, 그 이름이 같은 경우 스프링은 오류를 발생시킨다. ConflictingBeanDefinitionException 예외 발생
	@Component("service") //이런 식으로 같은 서비스 명을 써주었을 때

 

  • 수동 빈 등록 vs 자동 빈 등록 : 수동 빈 등록이 우선권을 가진다. (수동 빈이 자동 빈을 오버라이딩 해버린다.)

🔽 TEST

더보기
@Component
public class MemoryMemberRepository implements MemberRepository {}
@Configuration
@ComponentScan(
	excludeFilters = @Filter(type = FilterType.ANNOTATION, classes = Configuration.class)
)
public class AutoAppConfig {
	@Bean(name = "memoryMemberRepository")
	public MemberRepository memberRepository() {
		return new MemoryMemberRepository();
	}
}
Overriding bean definition for bean 'memoryMemberRepository' with a different
definition: replacing

설정 정보가 꼬이면 원인을 찾고 오류를 해결하기 힘들다. 스프링 부트는 이 경우 오류 발생하도록 기본 값을 바꾸었다. (설정 값 바꾸면 위와 같이 동작함)

Consider renaming one of the beans or enabling overriding by setting
spring.main.allow-bean-definition-overriding=true

 

스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술을 수강하며 기록한 글입니다.

반응형
반응형

AS-IS

스프링 없는 순수한 DI 컨테이너인 AppConfig는 요청을 할 때 마다 객체를 새로 생성하여 메모리 낭비가 심했다.

 

TO-BE

객체가 1개 생성되어 이를 공유하도록 설계 -> 싱글톤 패턴

 

 

TEST 싱글톤 예제

package hello.core.singleton;

public class SingletonService {
    //1. static 영역에 객체를 딱 1개만 생성해둔다.
    private static final SingletonService instance = new SingletonService();
    
    //2. public으로 열어서 객체 인스터스가 필요하면 이 static 메서드를 통해서만 조회하도록 허용한다.
    public static SingletonService getInstance() {
    	return instance;
    }
    
    //3. 생성자를 private으로 선언해서 외부에서 new 키워드를 사용한 객체 생성을 못하게 막는다.
    private SingletonService() {
    }
    
    public void logic() {
    	System.out.println("싱글톤 객체 로직 호출");
    }
}
@Test
@DisplayName("싱글톤 패턴을 적용한 객체 사용")
public void singletonServiceTest() {
    //new SingletonService();	// private으로 new 생성자 막음
    
    //1. 조회: 호출할 때 마다 같은 객체를 반환
    SingletonService singletonService1 = SingletonService.getInstance();
    
    //2. 조회: 호출할 때 마다 같은 객체를 반환
    SingletonService singletonService2 = SingletonService.getInstance();
    
    //참조값이 같은 것을 확인
    System.out.println("singletonService1 = " + singletonService1);
    System.out.println("singletonService2 = " + singletonService2);
    
    // singletonService1 == singletonService2
    assertThat(singletonService1).isSameAs(singletonService2);
    
    singletonService1.logic();
}

 

싱글톤 패턴 문제점
싱글톤 패턴을 구현하는 코드 자체가 많이 들어간다.
의존관계상 클라이언트가 구체 클래스에 의존한다. > DIP를 위반한다.**
클라이언트가 구체 클래스에 의존해서 OCP 원칙을 위반할 가능성이 높다.
테스트하기 어렵다.
내부 속성을 변경하거나 초기화 하기 어렵다.
private 생성자로 자식 클래스를 만들기 어렵다.
결론적으로 유연성이 떨어진다.
안티패턴으로 불리기도 한다.

 

**의존관계상 클라이언트가 구체 클래스에 의존한다. > DIP를 위반한다.

**MemberService라면 MemberServiceImpl의 getInstance() 가 필요하기 때문에 구체 클래스에 의존하는 셈이 된다!

@Bean
    public MemberService memberService() {
        return new MemebrServiceImpl.getInstance(~~);
    }

TEST 싱글톤 컨테이너 예제

 @Test
    @DisplayName("스프링 컨테이너와 싱글톤")
    void springContainer(){
        //AppConfig appConfig = new AppConfig();
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);

        MemberService memberService = ac.getBean("memberService", MemberService.class);
        MemberService memberService2 = ac.getBean("memberService", MemberService.class);

        System.out.println("memberService = " + memberService);
        System.out.println("memberService2 = " + memberService2);

        Assertions.assertThat(memberService).isSameAs(memberService2);          //인스턴스 값 비교
    }
싱글톤 컨테이너
스프링 컨테이너는 싱글턴 패턴을 적용하지 않아도, 객체 인스턴스를 싱글톤으로 관리한다.
이전에 설명한 컨테이너 생성 과정을 자세히 보자. 컨테이너는 객체를 하나만 생성해서 관리한다.
스프링 컨테이너는 싱글톤 컨테이너 역할을 한다. 이렇게 싱글톤 객체를 생성하고 관리하는 기능을 싱글톤
레지스트리라 한다.
스프링 컨테이너의 이런 기능 덕분에 싱글턴 패턴의 모든 단점을 해결하면서 객체를 싱글톤으로 유지할 수
있다.
싱글톤 패턴을 위한 지저분한 코드가 들어가지 않아도 된다.
DIP, OCP, 테스트, private 생성자로 부터 자유롭게 싱글톤을 사용할 수 있다.

싱글톤 방식의 주의점

  • stateful하게 설계하면 안된다. > stateless하게 설계해야함
  • 실무에서 정말 중요하게 생각하는 부분
  • 실제로는 멀티쓰레드로 구성. Service 메소드 내 getPrice를 하면서 오류 발생. (오류 잡기 힘들다!)
    • StatefulService 의 price 필드는 공유되는 필드인데, 특정 클라이언트가 값을 변경한다.
package hello.core.sigleton;

public class StatefulService {

    private int price; //상태를 유지하는 필드

    public void order(String name, int price){
        System.out.println("name = " + name + " price = " + price);
        this.price = price; //문제!!
    }

    public int getPrice() {
        return price;
    }
}

 

>> 클라이언트에서 price 값을 변경하지 못하도록 함.

package hello.core.sigleton;

public class StatefulService {

    //private int price; //상태를 유지하는 필드

    public int order(String name, int price){
        System.out.println("name = " + name + " price = " + price);
        //this.price = price; //문제!!

        return price;
    }

//    public int getPrice() {
//        //return price;
//    }
}
  • 문제 : 타 계정 ID 및 주문내역이 보임 > 복구하는게 힘들다
  • 스프링 빈은 항상 무상태로 설계하자!!!

@Configuration과 싱글톤

 

  • memberService : memberRepository() > new MemoryMemberRepository()
  • orderService : memberRepository() > new MemoryMemberRepository()
  • 결과적으로 각각 다른 2개의 MemoryMemberRepository가 생성되면서 싱글톤이 깨지는 것 처럼 보인다. (같은 객체를 2번 생성하므로)

 

그러나 memberRepository 인스턴스는 모두 같은 인스턴스가 공유되어 사용된다!!

 

더보기

appconfig 잘못 적어서 싱글톤 안지켜지고 있었음ㅋㅋ.,;;

제대로 수정 후 모두 같은 인스턴스가 공유되어 있음

 

* AppConfig에서 static 메서드로 구성하였기 때문

@Configuration과 @Bean의 조합으로 싱글톤을 보장하는 경우는 정적이지 않은 메서드일 때입니다.

https://www.inflearn.com/questions/609357

 

AppConfig에 호출 로그 남겨서 확인해본 결과 메소드 호출은 단 한번만 한다. 왜일까?! 🤔

call AppConfig.memberService
call AppConfig.memberRepository
call AppConfig.orderService

 


@Configuration과 바이트코드 조작의 마법

 

 public class ConfigurationSignletonTest {
 	@Test
    void configurationDeep(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
        AppConfig bean = ac.getBean(AppConfig.class);

        System.out.println("bean = " + bean);
        //순수한 class라면 class hello.core.AppConfig라고 출력되어야 함
    }
}

 

output

> bean = class hello.core.AppConfig$$EnhancerBySpringCGLIB$$bd479d70

 

AppConfig bean을 출력해보면 내가 만든 class로 나오는 것이 아닌 바이트 코드 조작 라이브러리를 사용해서 AppConfig 클래스 상속받은 임의의 다른 클래스를 만들어서 스프링 빈으로 등록시킴

 

@Bean
public MemberRepository memberRepository() {

	if (memoryMemberRepository가 이미 스프링 컨테이너에 등록되어 있으면?) {
		return 스프링 컨테이너에서 찾아서 반환;
	} else { //스프링 컨테이너에 없으면
		기존 로직을 호출해서 MemoryMemberRepository를 생성하고 스프링 컨테이너에 등록
		return 반환
	}
}

이런 식으로 생성하기 때문에 1번만 호출되는 것임

1번 생성하고 그 뒤로는 반환만 하기 때문에

 


 스프링이 어떻게 싱글톤을 보장할 수 있는지 알아볼 수 있었다. 다음은 컴포넌트 스캔에 대해서 알아보자.

 

 

 

스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술을 수강하며 기록한 글입니다.

반응형
반응형
//스프링 컨테이너 생성
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);

ApplicationContext(일반적으로 스프링 컨테이너로 칭함)

  • 인터페이스 ApplicationContext의 구현체 AnnotationConfigApplicationContext(AppConfig.class);
  • new AnnotationConfigApplicationContext(AppConfig.class);
    • 구성 정보인 AppConfig를 주면 스프링 컨테이너가 생성된다.
  • 스프링 컨테이너는 XML을 기반으로 만들 수 있고, 애노테이션 기반의 자바 설정 클래스로 만들 수 있다.
    • 스프링이 애노테이션 기반으로 잘 되어 있어서 XML 기반으로 만들 수 있지만 잘 사용하지 않는다
  • 스프링 컨테이너 생성과정

1. 스프링 컨테이너 생성

2. 스프링 빈 등록

스프링 컨테이너는 파라미터로 넘어온 설정 클래스 정보를 사용해서 스프링 빈을 등록한다.

  • @Bean 이 붙은 메소드를 호출. 메서드 이름을 빈 이름으로 return 값을 빈 객체로 등록
  • 빈 이름은 메서드 이름을 사용한다. 빈 이름을 직접 부여할 수 도 있다.
    • @Bean(name="memberService2")
  • 실무에서 무조건 명확하고 단순하게 빈 이름을 정해야 한다. 절대 중복되지 않도록!

 

3. 스프링 빈 의존관계 설정 - 준비

4. 스프링 빈 의존관계 설정 - 완료

스프링 컨테이너는 AppConfig.class 를 보고 의존관계 주입(DI)한다.

 

*싱글톤 컨테이너에서 추가 설명

 

스프링은 빈을 생성하고, 의존관계를 주입하는 단계가 나누어져 있다.
그런데 이렇게 자바 코드로 스프링 빈을 등록하면 생성자를 호출하면서 의존관계 주입도 한번에 처리된다.

**공부하기 위해서 sout 하는거지 실무에서는 눈으로 볼 수 없으니 시스템으로 작동하게 해야함

 

 

 

1-1. 컨테이너에 등록된 모든 빈 조회

  • ac.getBeanDefinitionNames() : 스프링에 등록된 모든 빈 이름을 조회
  • ac.getBean() : 빈 이름으로 빈 객체(인스턴스)를 조회


1-2. 애플리케이션 빈 출력하기 (내가 등록한 빈만)

  • getRole()
    ROLE_APPLICATION : 일반적으로 사용자가 정의한 빈
    ROLE_INFRASTRUCTURE : 스프링이 내부에서 사용하는 빈
더보기

* Junit5부터는 public 설정안해도 됨

* for문 자동 완성 : iter + Tap

package hello.core.beanfind;

import hello.core.AppConfig;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

class ApplicationContextInfoTest {

    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);

    @Test
    @DisplayName("모든 빈 출력하기")
    void findAllBean(){
        String[] beanDefinitionNames = ac.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            Object bean = ac.getBean(beanDefinitionName);
            System.out.println("beanDefinitionName = " + beanDefinitionName + " / object = " + bean);
        }
    }

    @Test
    @DisplayName("애플리케이션 빈 출력하기")
    void findApplicationBean(){
        String[] beanDefinitionNames = ac.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            BeanDefinition beanDefinition = ac.getBeanDefinition(beanDefinitionName);   //bean의 메타데이터

            // BeanDefinition.ROLE_INFRASTRUCTURE 스피링이 내부에서 사용하는 빈
            if(beanDefinition.getRole() == BeanDefinition.ROLE_APPLICATION){    //Application 개발을 위하여 등록한 Bean만 조회
                Object bean = ac.getBean(beanDefinitionName);
                System.out.println("beanDefinitionName = " + beanDefinitionName + " / object = " + bean);
            }

        }
    }
}

 

 

2. 스프링 빈 조회 - 기본

 

스프링 컨테이너에서 스프링 빈을 찾는 가장 기본적인 조회 방법

  • ac.getBean(빈이름, 타입)
  • ac.getBean(타입)

* NoSuchBeanDefinitionException

더보기
package hello.core.beanfind;

import hello.core.AppConfig;
import hello.core.member.Member;
import hello.core.member.MemberService;
import hello.core.member.MemebrServiceImpl;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import static org.assertj.core.api.Assertions.*;

class ApplicationContextBasicFindTest {

    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);

    @Test
    @DisplayName("빈 이름으로 조회")
    void findBeanName(){
        MemberService memberService = ac.getBean("memberService", MemberService.class); //ac.getBean(빈이름, 타입)
        //System.out.println("memberService = " + memberService);
        //System.out.println("memberService.getClass() = " +memberService.getClass());

        assertThat(memberService).isInstanceOf(MemebrServiceImpl.class); //memberService가 MemebrServiceImpl의 인스턴스인지
    }

    @Test
    @DisplayName("이름없이 타입으로만 조회")
    void findBeanType(){
        MemberService memberService = ac.getBean(MemberService.class); //ac.getBean(타입)
        assertThat(memberService).isInstanceOf(MemebrServiceImpl.class); //memberService가 MemebrServiceImpl의 인스턴스인지
    }

    @Test
    @DisplayName("구체타입으로 조회")
    void findBeanName2(){
        // 스프링에 등록된 인스턴스의 타입을 보기 때문에 인터페이스가 아닌 구체화를 적어주어도 됨
        // 하지만 역할과 구현을 분리하고 역할에 의존해야 한다. 즉, 다음과 같은 코드는 이상적이지 않다. (유연성이 떨어짐)
        MemberService memberService = ac.getBean("memberService", MemebrServiceImpl.class); //ac.getBean(빈이름, 타입)
        assertThat(memberService).isInstanceOf(MemebrServiceImpl.class); //memberService가 MemebrServiceImpl의 인스턴스인지
    }

    @Test
    @DisplayName("빈 이름으로 조회x")
    void findBeanNameX() {
        //ac.getBean("xxxx", MemberService.class);   //NoSuchBeanDefinitionException
        org.junit.jupiter.api.Assertions.assertThrows(NoSuchBeanDefinitionException.class,  
                () -> ac.getBean("xxxx", MemberService.class)); //이 로직을 실행하면 //다음과 같은 에러가 터져야 성공
    }
}

 

3. 스프링 빈 조회 - 동일한 타입이 둘 이상

 

* NoUniqueBeanDefinitionException 발생 : 타입으로 조회시 같은 타입의 스프링 빈이 둘 이상

 

  • 빈 이름을 지정 필요
  • ac.getBeansOfType() 을 사용하면 해당 타입의 모든 빈을 조회할 수 있다.
더보기
package hello.core.beanfind;

import hello.core.AppConfig;
import hello.core.discount.DiscountPolicy;
import hello.core.member.MemberRepository;
import hello.core.member.MemoryMemberRepositroy;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;

public class ApplicationContextSameBeanFindTest {

    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SameBeanConfig.class);

    @Test
    @DisplayName("타입으로 조회 시 같은 타입이 둘 이상있으면 중복 오류가 발생한다.")
    void FindBeanByTypeDuplicate() {
        //MemberRepository bean = ac.getBean(MemberRepository.class); //NoUniqueBeanDefinitionException
        assertThrows(NoUniqueBeanDefinitionException.class,
                () -> ac.getBean(MemberRepository.class));
    }

    @Test
    @DisplayName("타입으로 조회 시 같은 타입이 둘 이상 있으면 빈 이름을 지정하면 된다")
    void findBeanByName() {
        // 디테일하게 테스트 시 memberRepository1 리턴 인스턴스에 파라미터 값 넣어서 내부 값 꺼내서 검증하는 방법(지금은 스프링 믿고 가자)
        MemberRepository memberRepository = ac.getBean("memberRepository1", MemberRepository.class);
        org.assertj.core.api.Assertions.assertThat(memberRepository).isInstanceOf(MemberRepository.class);
    }

    @Test
    @DisplayName("특정 타입을 모두 조회하기")
    void findALLBeanByType(){
        //Autowired로 자동주입할 때 이런 기능이 다 적용이 됨
        Map<String, MemberRepository> beansOfType = ac.getBeansOfType(MemberRepository.class);
        for (String key : beansOfType.keySet()) {
            System.out.println("key = " + key + " value = " + beansOfType.get(key)) ;
        }

        System.out.println("beansOfType = " + beansOfType);
        org.assertj.core.api.Assertions.assertThat(beansOfType.size()).isEqualTo(2);

    }
    

    @Configuration
    static class SameBeanConfig {
        //static : class 안에서 class를 쓴다는 것은 내부에서만 사용하겠다는 뜻

        //아래와 같이 Bean의 이름이 다르고 객체의 인스턴스 가입이 같을 수 있음.
        // 파라미터로 "10", "1000"를 보내면 한번에 성능을 N개 씩 저장하는 레포지터리로 설정할 때
        @Bean
        public MemberRepository memberRepository1() {
            return new MemoryMemberRepositroy();
        }

        @Bean
        public MemberRepository memberRepository2() {
            return new MemoryMemberRepositroy();
        }
    }

}

 

4. 스프링 빈 조회 - 상속 관계

  • 부모 타입으로 조회하면, 자식 타입도 함께 조회한다.
  • Object 타입으로 조회하면, 모든 스프링 빈을 조회한다.
눈에 안보이지만(생략돼서) Java 최상위 부모는 Object 다. (extends Object)

 

  • ApplicationContext에서 직접 getBean 할 일이 별로 없다. 스프링 컨테이너가 자동 주입하거나 @Bean 으로 해서 구현체에서 따로 Bean을 조회할 일이 없음
  • 굳이 설명한 이유는 기본 원리이기도 하고 가끔 순수한 자바 애플리케이션에서 스프링 컨테이너를 생성할 상황이 있을 수도 있음
  • 또한 부모 타입을 조회 시 자식이 어디까지 조회되는지 파악하면 자동 의존관계에서 문제 없이 잘 해결할 수 있음
더보기

* static import 활용하기..!

package hello.core.beanfind;

import hello.core.AppConfig;
import hello.core.discount.DiscountPolicy;
import hello.core.discount.FixDiscountPolicy;
import hello.core.discount.RateDiscountPolicy;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;

public class ApplicationContextExtendsFindTest {

    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(TestConfig.class);

    @Test
    @DisplayName("부모 타입으로 조회 시, 자식이 둘 이상있으면 중복 오류가 발생한다.")
    void findBeanByParentTypeDuplicate() {
        //DiscountPolicy bean = ac.getBean(DiscountPolicy.class);
        assertThrows(NoUniqueBeanDefinitionException.class,
                () -> ac.getBean(DiscountPolicy.class));
    }


    @Test
    @DisplayName("부모 타입으로 조회 시, 자식이 둘 이상있으면 빈 이름을 지정하면 된다.")
    void findBeanByParentTypeBeanName() {

        DiscountPolicy rateDiscountPolicy = ac.getBean("rateDiscountPolicy", DiscountPolicy.class);
        org.assertj.core.api.Assertions.assertThat(rateDiscountPolicy).isInstanceOf(RateDiscountPolicy.class);
    }

    @Test
    @DisplayName("특정 하위 타입으로 조회")
    void findBeanBySubType() {
        //좋은 방법은 아니다.
        RateDiscountPolicy bean = ac.getBean(RateDiscountPolicy.class);
        org.assertj.core.api.Assertions.assertThat(bean).isInstanceOf(RateDiscountPolicy.class);
    }

    @Test
    @DisplayName("부모 타입으로 모두 조회하기")
    void findAllBeanByParentType() {
        Map<String, DiscountPolicy> beansOfType = ac.getBeansOfType(DiscountPolicy.class);
        org.assertj.core.api.Assertions.assertThat(beansOfType.size()).isEqualTo(2);
        for (String key : beansOfType.keySet()) {
            System.out.println("key = " + key + " value = " + beansOfType.get(key));
        }
        System.out.println("beansOfType = " + beansOfType);
    }

    @Test
    @DisplayName("Object로 모든 빈 조회하기")
    void findAllBeansByObjectType(){
        //스프링 컨테이너에 등록된 모든 빈 출력
        Map<String, Object> beansOfType = ac.getBeansOfType(Object.class);
        for (String key : beansOfType.keySet()) {
            System.out.println("key = " + key + " value = " + beansOfType.get(key));
        }
    }

    @Configuration
    static class TestConfig{
        @Bean
        public DiscountPolicy rateDiscountPolicy(){
            // DiscountPolicy > RateDiscountPolicy 해도 똑같지만, 역할과 구현을 쪼갠 것임
            // 의존관계 주입 시에도 DiscountPolicy을 보고 있으니 인터페이스만 보면 됨.
            return new RateDiscountPolicy();
        }

        @Bean
        public DiscountPolicy fixDiscountPolicy(){
            return new FixDiscountPolicy();
        }
    }
}

BeanDefinition : 빈 설정 메타정보

 

  • @Bean , <bean> 당 각각 하나씩 메타 정보가 생성된다. (각각 Java class, XML)
  • 스프링 컨테이너는 이 메타정보를 기반으로 스프링 빈을 생성한다
스프링은 BeanDefinition으로 스프링 빈 설정 메타 정보를 추상화한다.

스프링 빈을 만드는 방법

  1. 직접적으로 등록
  2. 팩토리 빈을 통해서 등록(일반적인 Java Config)
  • JSON 등 과 같은 형태로 임의의 Config 파일을 생성하여 설정 정보를 구성할 수 있다.
  • AppConfig.class > 팩소리메소드 패턴
    • factoryBeanName, factoryMethodName 가 출력됨 팩토리빈을 통해서 생성
  • xml 에는 위 데이터가 출력되지 않고 Class 정보가 직접적으로 드러나짐
    • class 메타데이터가 있고 factoryBeanName, factoryMethodName은 null인 것을 확인할 수 있다.
beanDefinition = Generic bean: class [hello.core.discount.RateDiscountPolicy]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; …

 

 

스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술을 수강하며 기록한 글입니다.

반응형
반응형

 

package hello.core;

import hello.core.discount.DiscountPolicy;
import hello.core.discount.FixDiscountPolicy;
import hello.core.discount.RateDiscountPolicy;
import hello.core.member.MemberService;
import hello.core.member.MemebrServiceImpl;
import hello.core.member.MemoryMemberRepositroy;
import hello.core.order.OrderService;
import hello.core.order.OrderServiceimpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public MemberService memberService() {
        return new MemebrServiceImpl(memberRepository());
    }

    @Bean
    public static MemoryMemberRepositroy memberRepository() {
        return new MemoryMemberRepositroy();
    }

    @Bean
    public OrderService orderService() {
        return new OrderServiceimpl(memberRepository(), discountPolicy());
    }

    @Bean
    public DiscountPolicy discountPolicy(){
        //return new RateDiscountPolicy();
        return new FixDiscountPolicy();
    }
}

 

1. Class 상단에 @Configuration 넣기

AppConfig에 설정을 구성한다는 뜻

 

2. 각 메서드에 @Bean 넣기

스프링 컨테이너에 스프링 빈으로 등록됨

 

public class OrderApp {
    public static void main(String[] args) {
        //main 메서드보다 test에서 테스트 필요!
/*        AppConfig appConfig = new AppConfig();
        MemberService memberService = appConfig.memberService();
        OrderService orderService = appConfig.orderService();*/

        ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
        MemberService memberService = ac.getBean("memberService", MemberService.class);
        OrderService orderService = ac.getBean("orderService", OrderService.class);

        Long memberId = 1L;
        Member member = new Member(memberId, "memberA", Grade.VIP);
        memberService.join(member);

        Order order = orderService.createOrder(memberId, "pizza", 5000);

        System.out.println(order);
        System.out.println(order.getDiscountPrice());
    }
}

주석된 코드는 기존에 스프링이 아닌 자바로 AppConfig를 사용해서 직접 객체 생성하고 DI를 한 코드

 

🍰ApplicationContext : 스프링 컨테이너(@Bean 관리)

 

스프링 컨테이너는 @Configuration 이 붙은 AppConfig 를 설정(구성) 정보로 사용한다. 여기서 @Bean
이라 적힌 메서드를 모두 호출해서 반환된 객체를 스프링 컨테이너에 등록한다. 이렇게 스프링 컨테이너에
등록된 객체를 스프링 빈이라 한다.

 

스프링 빈은 applicationContext.getBean() 메서드를 사용해서 찾을 수 있다.

 

- 스프링 빈의 이름

@Bean 이 붙은 메서드의 명을 스프링 빈의 이름으로 사용하지만 다음과 같이 임의 설정이 가능하다.

(하지만, 관례에 따르는 것을 추천함)

//AppConfig
@Bean(name = "abc")

//OrderApp
OrderService orderService = ac.getBean("abc", OrderService.class);


이 전 강의에서는 직접 Java 코드로 구성을 하였는데 이제 스프링 컨테이너가 담당하게 되었다. 언뜻보면 더 복잡해보일 수 도 있는데 스프링 컨테이너의 역할이 프로젝트에 있어서 큰 역할을 차지한다. 어떠한 부분 때문에 이러한 스프링 컨테이너를 사용하는지 궁금하다!

 

 

스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술을 수강하며 기록한 글입니다.

반응형
반응형

 

public class OrderServiceimpl implements OrderService{
    private final MemberRepository memberRepository = new MemoryMemberRepositroy();
    private final DiscountPolicy discountPolicy = new RateDiscountPolicy();
}

 


  • 단일책임원칙(SRP) : 한 클래스는 하나의 책임만 가져야 한다.

클라이언트 객체는 직접 구현 객체 생성, 연결, 실행 중

 

🍰 관심사 분리 필요 : AppConfig에서 구현 객체 생성 및 연결하는 책임

 


  • 의존관계 역전 원칙(DIP) : 구체화가 아닌 추상화에 의존해야 한다.

OrderServiceimpl이 추상화 인터페이스(DiscountPolicy)에 의존하는 것은 맞지만 구체화 구현 클래스(RateDiscountPolicy)에도 의존 중

 

public class OrderServiceimpl implements OrderService{
    private final MemberRepository memberRepository;
    private final DiscountPolicy discountPolicy;
}

🤢[NullPointException 발생!] 클라이언트 코드가 추상화 인터페이스에만 의존하도록 코드를 변경하면 클라이언트 코드는 인터페이스만으로는 아무것도 실행할 수 없음

 

🍰 클라이언트에 의존 관계 주입 : 클라이언트 코드 대신 AppConfig가 RateDiscountPolicy 객체 인스턴스 생성


  • 개방 폐쇄 원칙(OCP) : 확장에는 열려 있으나 변경에는 닫혀 있다.

기존에는 클라이언트 소스 코드를 변경하여 어떠한 구체화 구현 클래스를 의존할지 지정해주었음


🍰 애플리케이션을 사용 영역과 구성 영역으로 나누기 : 고정 할인 정책에서 정률 할인 정책으로 바뀌었을 경우 AppConfig에서 FixDiscountPolicy > RateDiscountPolicy으로만 수정하면 AppConfig가 의존관계를 변경해서 클라이언트 코트에 주입함. 구성 영역에서 처리하므로 사용 영역인 클라이언트 코드 수정이 불필요함.

 

*다형성 사용하고 클라이언트가 DIP를 지킴으로서 OCP를 지키기 좋은 코드가 됨.


 

🎂 SRP / DIP / OCP를 준수하여 수정한 코드

 

OrderServiceimpl

public class OrderServiceimpl implements OrderService{
    private final MemberRepository memberRepository;
    private final DiscountPolicy discountPolicy;

    public OrderServiceimpl(MemberRepository memberRepository, DiscountPolicy discountPolicy) {
        this.memberRepository = memberRepository;
        this.discountPolicy = discountPolicy;
    }
    ...
 }

추상화 인터페이스에만 의존하고 생성자를 통해 의존 관계 주입

> OrderServiceImpl 은 필요한 인터페이스들을 호출하지만 어떤 구현 객체들이 실행될지 모른다.

 

AppConfig

public class AppConfig {

    public MemberService memberService() {
        return new MemebrServiceImpl(memberRepository());
    }

    private static MemoryMemberRepositroy memberRepository() {
        return new MemoryMemberRepositroy();
    }

    public OrderService orderService() {
        return new OrderServiceimpl(memberRepository(), new RateDiscountPolicy());
    }

    public DiscountPolicy discountPolicy(){
        return new RateDiscountPolicy();
    }
}

 

  • 제어의 역전 IoC(Inversion of Control) : 프로그램의 제어 흐름을 직접 제어하는 것이 아니라 외부에서 관리하는 것

 

기존 프로그램은 클라이언트 구현 객체가 스스로 필요한 서버 구현 객체를 생성하고, 연결하고, 실행했다.
프로그램의 제어 흐름은 AppConfig가 담당하고 관리함 (OrderServiceImpl도 AppConfig가 생성함) 

 

프레임워크 vs 라이브러리
프레임워크 : Appconfig나 프레임워크에 해당. 내가 작성한 코드를 제어하고, 대신 실행 (JUnit)
라이브러리 : 내가 작성한 코드가 직접 제어의 흐름을 담당

 

  • 의존관계 주입 DI(Dependency Injection)


- 정적인 클래스 의존관계
정적 클래스 의존관계는 실행없이 import 코드만 보고 의존관계를 쉽게 파악 가능

OrderServiceImpl ➡ MemberRepository / DiscountPolicy 

 

실제 어떤 객체가 OrderServiceImpl 에 주입 될지 알 수 없고 동적인 객체 인스턴스 의존 관계를 봐야함

 

 

- 동적인 객체 인스턴스 의존 관계
애플리케이션 실행 시점에 실제 생성된 객체 인스턴스의 참조가 연결된 의존 관계

애플리케이션 실행 시점(런타임)에 외부에서 실제 구현 객체를 생성하고 클라이언트에 전달해서
클라이언트와 서버의 실제 의존관계가 연결 되는 것을 의존관계 주입(DI)이라 한다.

정적인 클래스 의존관계를 변경하지 않고, 동적인 객체 인스턴스 의존관계를 변경할 수 있다.

즉, 애플리케이션 소스를 수정하지 않고 Rate냐 Fixed나 수정 가능하다는 뜻

 

객체 인스턴스를 생성하고, 그 참조값을 전달해서 연결

 

public class OrderServiceimpl implements OrderService{
    private final MemberRepository memberRepository;
    private final DiscountPolicy discountPolicy;
}

 

> memberRepository, discountPolicy의 인스턴스의 참조값(MemoryMemberRepositroy/RateDiscountPolicy)으로 구성되어 있음

 

  •  IoC 컨테이너, DI 컨테이너(어샘블러, 오브젝트 팩토리)

AppConfig 처럼 객체를 생성하고 관리하면서 의존관계를 연결해 주는 것

 

 

 

 

출처 : 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

반응형
반응형

  1. 주문 생성: 클라이언트(Main / Spring의 경우 Controller)는 주문 서비스에 주문 생성을 요청한다.
  2. 회원 조회: 할인을 위해서는 회원 등급이 필요하다. 그래서 주문 서비스는 회원 저장소에서 회원을 조회한다.
  3. 할인 적용: 주문 서비스는 회원 등급에 따른 할인 여부를 할인 정책에 위임한다.
  4. 주문 결과 반환: 주문 서비스는 할인 결과를 포함한 주문 결과를 반환한다.

참고: 실제로는 주문 데이터를 DB에 저장하겠지만, 예제가 너무 복잡해 질 수 있어서 생략하고, 단순히 주문 결과를 반환한다. (실제 프로젝트의 경우 상품 객체가 필요)

 

*해당 코드는 차후 스프링 프레임워크 이해를 위한 JAVA로만 작성된 코드임


괴랄한 코드의 탄생.

public class OrderServiceimpl implements OrderService{
    private MemberRepository memberRepository = new MemoryMemberRepositroy();
    private DiscountPolicy discountPolicy = new FixDiscountPolicy();

    @Override
    public void order(Order order) {

        Member member = memberRepository.findById(order.getId());

        if(member.getGrade() == Grade.VIP) {
            order.setPrice(order.getPrice() - discountPolicy.discount(order));
        }
    }
}

1) 리턴을 왜 안해주며 클라이언트 단에서 받는 매개변수는 어디로

2) 왜 주문 서비스 구현체에서 할인 정책을 구현하는지 (단일책임원칙에 위배)

+) 생성자 주입

 


OrderServiceimpl

 

public class OrderServiceTest {

    MemberService memberService = new MemebrServiceImpl();
    OrderService orderService = new OrderServiceimpl();

    @Test
    void createOrder(){
        Long memberId = 1L; //primitive Type은 NULL을 넣을 수 없음
        Member member = new Member(memberId, "memberA", Grade.VIP);
        memberService.join(member);

        Order order = orderService.createOrder(memberId, "pizza", 5000);

        Assertions.assertThat(order.getDiscountPrice()).isEqualTo(1000);
    }
}

 

FixDiscountPolicy

할인 정책 클래스에겐 할인 관련  로직만

public class FixDiscountPolicy implements DiscountPolicy {

    private int discountFixAmount = 1000;

    @Override
    public int discount(Member member, int price) {
        if(member.getGrade() == Grade.VIP) {
            return discountFixAmount;
        } else {
            return 0;
        }
    }
}

Order

public class Order {
    private long memberId;
    private String itemName;
    private int itemPrice;
    private int discountPrice;
    
    //constructor
    //getter and setter
    //toString()
}

TEST

public class OrderServiceTest {

    MemberService memberService = new MemebrServiceImpl();
    OrderService orderService = new OrderServiceimpl();

    @Test
    void createOrder(){
        Long memberId = 1L; //primitive Type은 NULL을 넣을 수 없음
        Member member = new Member(memberId, "memberA", Grade.VIP);
        memberService.join(member);

        Order order = orderService.createOrder(memberId, "pizza", 5000);

        Assertions.assertThat(order.getDiscountPrice()).isEqualTo(1000);
    }
}

 

출처 : 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

반응형
반응형

JDBC, JDBCTemplate 강의에서의 큰 수확은 스프링의 장점인 개방 폐쇄의 원칙, 다형성을 이해할 수 있다는 점이었다. 스프링 DB접근 기술 쪽은 이 부분을 중점적으로 포스팅

 

강의 비지니스 시나리오는 DB가 정해져 있지 않아 Memory로 repository를 구성했었다.

이를 H2 데이터베이스를 연결하고 JDBC로 구현체를 변경이 필요했다.

 

🎈🎈 개방-폐쇄 원칙(OCP, Open-Closed Principle) :확장에는 열려있고, 수정/변경에는 닫혀있다. 

DataSource dataSource;

@Autowired
public SpringConfig(DataSource dataSource) {
    this.dataSource = dataSource;
}
        
@Bean
    public MemberRepository memberRepository(){
        //new 키워드 뒤에 인터페이스 구현 클래스
        //return new MemoryMemberRepository();
        return new JdbcMemberRepostiory(dataSource);
    }

스프링의 DI (Dependencies Injection)을 사용하면 기존 코드를 전혀 손대지 않고, 설정(어셈블리 라인)만으로 구현 클래스(구현체)를 변경할 수 있다.

 

>> 객체지향의 다형성을 활용

Service 단에서 어떤 Repository를 의존할지 기존 코드를 다 수정해야하지만 DI를 사용하면 SpringConfig만 손봐주면 된다는 말

 


이후에 JDBCTemplate , JPA, 스프링 데이터 JPA도 동일하게 구현체를 쉽게 변경할 수 있었다.

🎈🎈JDBCTemplate 

DataSource dataSource;

@Autowired
public SpringConfig(DataSource dataSource) {
    this.dataSource = dataSource;
}
        
@Bean
    public MemberRepository memberRepository(){
        //new 키워드 뒤에 인터페이스 구현 클래스
        //return new MemoryMemberRepository();
        //return new JdbcMemberRepostiory(dataSource);
        return new JdbcTemplateMemberRepository(dataSource);
    }

 

🎈🎈JPA

//@PersistenceContext
private EntityManager em;

@Autowired
public SpringConfig(EntityManager em) {
    this.em = em;
}

@Bean
public MemberRepository memberRepository(){
    //new 키워드 뒤에 인터페이스 구현 클래스
    //return new MemoryMemberRepository();
    //return new JdbcMemberRepostiory(dataSource);
    //return new JdbcTemplateMemberRepository(dataSource);
    return new JpaMemberRepository(em);
}

 

+) 엔티티 매핑 필요

@Entity
public class Member {
	@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	...
 }

*참고) build.gradle 수정, resources/application.properties 수정도 필요 

 

🎈🎈스프링 데이터 JPA

: JpaRepository를 상속하는 인터페이스를 만들면 자동으로 구현체를 등록해준다. (Repository bean등록 안해도 됨)

@Configuration
public class SpringConfig {
 	private final MemberRepository memberRepository;

	public SpringConfig(MemberRepository memberRepository) {
	 	this.memberRepository = memberRepository;
	 }
	 @Bean
	 public MemberService memberService() {
	 	return new MemberService(memberRepository);
 }
}

 

출처 : 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

반응형
반응형
javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save()

오류 : JPA를 사용할 때 PK인 컬럼을 도메인에 설정해주어야 함

 

해결 : @GeneratedValue 자동생성

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

*식별자를 직접 할당하는 방법도 있음

반응형