Spring Boot 공부 일기<3> - @Qualifier, @Primary, Lazy Initialization

이동휘·2024년 8월 7일

Spring Boot

목록 보기
3/21

1. IDE

Intellij

2. 오늘 공부 내용

@Qualifier, @Primary

  • @Qualifier - 의존성 주입 과정에서 특정 빈을 선택할 때 사용하는 애너테이션, 어떤 빈을 주입해야 할지 명확하게 지정하기 위해 사용
  • @Primary - 기본적으로 주입될 빈을 지정할 수 있음
  • @Qualifier가 @Primary보다 우선적으로 적용됨

사용 예시

public interface GreetingService {
    void greet();
}

@Service
public class EnglishGreetingService implements GreetingService {
    @Override
    public void greet() {
        System.out.println("Hello");
    }
}

@Service
public class SpanishGreetingService implements GreetingService {
    @Override
    public void greet() {
        System.out.println("Hola");
    }
}
@Component
public class MyController {

    private final GreetingService greetingService;

    @Autowired
    public MyController(@Qualifier("englishGreetingService") GreetingService greetingService) {
        this.greetingService = greetingService;
    }
}
@Service
@Primary
public class DefaultGreetingService implements GreetingService {
    @Override
    public void greet() {
        System.out.println("Default Greeting");
    }
}

요약

  • @Qualifier는 동일한 타입의 여러 빈이 있을 때, 어떤 빈을 주입할지 명시적으로 지정하기 위해 사용됩니다.
  • @Qualifier@Autowired와 함께 사용되며, 모호성을 해결하는 데 중요한 역할을 합니다.
  • @Primary는 기본 빈을 지정하지만, @Qualifier가 우선 적용됩니다.

Lazy Initialization(지연 초기화)

  • 즉시 초기화(Eager Initialization) - 애플리케이션이 시작될 때 모든 빈이나 객체를 즉시 생성하고 초기화하는 방식, 시작할 떄 약간의 오버헤드가 발생하지만, 런타임 중에는 객체를 바로 사용 가능
  • 지연 초기화(Lazy Initialization) - 객체나 빈이 실제로 필요할 떄까지 초기화를 지연시키는 방식, 이 방식은 메모리 사용을 줄이고, 애플리케이션의 시작 시간을 단축하는데 유리

Sprung Lazy Initialization

  • @Lazy 애너테이션 - 애너테이션 추가시 빈은 실제로 요청될 때까지 초기화하지 않음
@Service
@Lazy
public class MyService {
    public MyService() {
        System.out.println("MyService bean is initialized");
    }
}
@Component
public class MyController {

    private final MyService myService;

    @Autowired
    public MyController(@Lazy MyService myService) {
        this.myService = myService;
    }
}

Lazy Initialization 장단점

  • 장점
    • 성능 최적화 - 불필요한 빈 초기화를 피함으로써 메모리 사용을 줄이고 애플리케이션 시작 시간을 단축할 수 있음
    • 리소스 절약 - 특정 빈이나 리소스가 사용되지 않을 가능성이 있는 경우. 이를 지연 초기화하여 자원을 효율적으로 사용
    • 디펜던시 관리 - 특정 조건에서만 필요한 의존성을 지연 초기화하여, 필요한 시점에만 생성되도록 함
  • 단점
    • 지연된 오류 발견 - 초기화가 지연되면서 객체 생성 시점에 발생할 수 잇는 오류가 늦게 발견될 수 있음
    • 복잡성 증가 - 지연 초기화를 잘못 사용하면 애플리케이션의 동작이 예측하기 어려워질 수 있음
    • 성능 저하 - 실제로 객체가 필요할 떄 초기화가 이루어지므로, 첫 번째 사용 시 성능이 저하될 수 있음

전체 애플리케이션의 지연 초기화 설정

spring:
  main:
    lazy-initialization: true

정리

  • Lazy Initialization은 객체의 초기화를 필요할 때까지 미루는 방식으로, 메모리 사용과 애플리케이션 시작 시간을 최적화할 수 있습니다.
  • Spring에서 @Lazy 애너테이션을 사용하여 개별 빈이나 의존성을 지연 초기화할 수 있습니다.
  • 이 방법은 성능과 리소스 최적화에 유리하지만, 잘못 사용하면 복잡성을 증가시키고 오류가 늦게 발견될 수 있습니다.

0개의 댓글