@Lazy

2023. 5. 30. 17:35기술 창고/어노테이션 창고

728x90
반응형
SMALL

@Lazy

Lazy 어노테이션은 초기화를 지연시키는 어노테이션입니다.

Spring은 기본적으로 즉시 초기화를 기본값으로 가지고 있습니다.

 

Lazy 어노테이션을 적용하게 되면 해당 클래스 객체를 사용하려고 할 때 초기화가 되어 사용되게 됩니다.

 

// 초기화는 기본적으로 EAGER (즉시) 방식으로 된다. 어플리케이션을 실행하면 기본적으로 바로 Component 객체가 생성되고 autowiring이 되는 것이다.
// @Lazy 어노테이션을 통해 초기화를 늦출 수 있다.
// 지연 초기화를 적용할 경우 해당 Component 객체를 호출해줘야 그 때 초기화되고 호출된다.
@Component
class ClassA{

}

@Component
@Lazy
class ClassB{

    private ClassA classA;

    public ClassB(ClassA classA){
        System.out.println("Some Initialization logic");
        this.classA = classA;
    }

    public void doSomething(){
        System.out.println("Do Something");
    }
}

@Configuration
@ComponentScan
public class LazyInitializationLauncherApplication {

    public static void main(String[] args) {

        try (var context = new AnnotationConfigApplicationContext(LazyInitializationLauncherApplication.class)) {
//            Arrays.stream(context.getBeanDefinitionNames()).forEach(System.out::println);
            System.out.println("Initialization of context is completed");
            context.getBean(ClassB.class).doSomething(); // 지연시킨 ClassB 객체를 사용하려고 하므로 이때 초기화가 진행.
        }

    }
}

 

지연 초기화 vs 즉시 초기화

 

 

초기화에서는 보통 지연 초기화보다 기본적인 즉시 초기화를 선호한다고 합니다.

즉시 초기화는 어플리케이션 구성 단계에서부터 오류가 발생하면 잡아낼 수 있기 때문입니다.

지연 초기화는 지연되기 때문에 오류를 발생시켜서 잡으려면 해당 객체를 사용해야만 오류를 발견할 수 있습니다.

즉, 런타임 단계에서 오류를 발견할 수 있을 것 입니다.

 

728x90
반응형
LIST

'기술 창고 > 어노테이션 창고' 카테고리의 다른 글

@PostConstruct / @PreDestroy  (0) 2023.05.30
@Scope  (0) 2023.05.30
@Primary  (0) 2023.05.30
@Qualifier  (0) 2023.05.30
@ComponentScan  (0) 2023.05.30