[Spring๐ฑ] Bean ์ง์ฐ ์ด๊ธฐํ,์ฆ์ ์ด๊ธฐํ
/ 4 min read
Table of Contents
๐ Spring์์์ ์ด๊ธฐํ ๋ฐฉ์: Lazy vs Eager
Spring์์ ๋น(bean)์ ์ด๊ธฐํํ๋ ๋ ๊ฐ์ง ๋ฐฉ์์ธ ์ง์ฐ ์ด๊ธฐํ(Lazy Initialization)์ ์ฆ์ ์ด๊ธฐํ(Eager Initialization)๊ฐ ์๋ค.
๐ ์ฆ์ ์ด๊ธฐํ (Eager Initialization)
Spring์ ๊ธฐ๋ณธ ์ค์ ์ ์ฆ์ ์ด๊ธฐํ์ด๋ค.
์ปจํ
์ด๋๊ฐ ์์ฑ๋ ๋ ๋ชจ๋ ๋น์ ์ฆ์ ์์ฑํ๊ณ ์ด๊ธฐํ ํ๋ค.
์ ํ๋ฆฌ์ผ์ด์
์คํ ์ ๋น์ด ์ด๋ฏธ ์ค๋น๋์ด ์์ด, ๋ฐ๋ก ์ฌ์ฉ ๊ฐ๋ฅํ๋ค๋ ์ฅ์ ์ด ์๋ค.
์ฅ์
- ์ ํ๋ฆฌ์ผ์ด์ ์ด ์คํ๋๋ ๋์์๋ ๋น ์ด๊ธฐํ ์ง์ฐ์ด ์์ด ์ฑ๋ฅ์ด ์์ ์ .
- ์ด๊ธฐํ๊ฐ ๋นจ๋ฆฌ ์ด๋ฃจ์ด์ง๋ฏ๋ก ๋๋ฒ๊น ์ ๋ฒ๊ทธ๋ฅผ ์ฝ๊ฒ ์ฐพ์ ์ ์์.
๋จ์
- ํ์ ์๋ ๋น๋ ์ด๊ธฐํํ๋ฏ๋ก ๋ฉ๋ชจ๋ฆฌ ๋ญ๋น๊ฐ ์์ ์ ์์.
- ์ ํ๋ฆฌ์ผ์ด์ ์์ ์๊ฐ์ด ๊ธธ์ด์ง ์ ์์.
โณ ์ง์ฐ ์ด๊ธฐํ (Lazy Initialization)
์ง์ฐ ์ด๊ธฐํ๋ ์ ํ๋ฆฌ์ผ์ด์
์คํ ์ ๋ชจ๋ ๋น์ ์ด๊ธฐํํ์ง ์๊ณ , ํ์ํ ๋ ์ด๊ธฐํํ๋ ๋ฐฉ์.
@Lazy
์ด๋
ธํ
์ด์
์ ์ฌ์ฉํ๋ฉด ํน์ ๋น๋ง ์ง์ฐ ์ด๊ธฐํํ ์๋ ์๊ณ , ์ ์ฒด ๋น์ ๋ํด ์ง์ฐ ์ด๊ธฐํ๋ฅผ ํ์ฑํํ ์๋ ์์ด.
์ฅ์
- ์ ํ๋ฆฌ์ผ์ด์ ์์ ์๊ฐ์ด ๋จ์ถ๋ผ ์ด๊ธฐ ๋ก๋ฉ์ด ๋นจ๋ผ์ง.
- ๋ฉ๋ชจ๋ฆฌ ์ ์ฝ ๊ฐ๋ฅ.
๋จ์
- ๋น์ ํธ์ถํ๋ ์์ ์ ์ด๊ธฐํ๋๋ฏ๋ก ์ฑ๋ฅ์ ์ํฅ์ ์ค ์ ์์.
- ์ด๊ธฐํ ํ์ด๋ฐ์ด ๋ช ํํ์ง ์์ ๋๋ฒ๊น ์ด ์ด๋ ค์ธ ์ ์์.
๐ ์์ ์ฝ๋
package com.example.lazyinitialization;
import org.springframework.context.annotation.*;
@Componentclass ClassA { public ClassA() { System.out.println("ClassA initialized"); }}
@Component@Lazyclass ClassB { private final ClassA classA;
public ClassB(ClassA classA) { System.out.println("ClassB initialized"); this.classA = classA; }
public void doSomething() { System.out.println("Doing something..."); }}
@Configuration@ComponentScanpublic class LazyInitializationExample {
public static void main(String[] args) { var context = new AnnotationConfigApplicationContext(LazyInitializationExample.class); System.out.println("Context initialized");
context.getBean(ClassB.class).doSomething(); }}
๐ฅ๏ธ ์ถ๋ ฅ ๊ฒฐ๊ณผ
์คํ๊ฒฐ๊ณผ๋ ์๋์ ๊ฐ์:
ClassA initializedContext initializedClassB initializedDoing something...
๐ ์์ฝ
- ์ฆ์ ์ด๊ธฐํ: ์ปจํ ์ด๋๊ฐ ์์ฑ๋ ๋ ๋น์ ๋ชจ๋ ์ด๊ธฐํํจ. ์ ํ๋ฆฌ์ผ์ด์ ์คํ ์ค ์ฑ๋ฅ์ด ์์ ์ ์ด์ง๋ง ๋ฉ๋ชจ๋ฆฌ ๋ญ๋น๊ฐ ๋ฐ์ํ ์ ์์.
- ์ง์ฐ ์ด๊ธฐํ: ํ์ํ ์์ ์ ๋น์ ์ด๊ธฐํํจ. ๋ฉ๋ชจ๋ฆฌ ์ ์ฝ๊ณผ ๋น ๋ฅธ ์ด๊ธฐ ๋ก๋ฉ์ด ๊ฐ๋ฅํ์ง๋ง, ์ฑ๋ฅ์ ์ํฅ์ ์ค ์ ์์.
๐ก ํ
์ง์ฐ ์ด๊ธฐํ๋ ๋ฉ๋ชจ๋ฆฌ์ ์ฑ๋ฅ ์ต์ ํ๊ฐ ํ์ํ ๋ ์ ์ฉํจ.
ํ์ง๋ง ๋ชจ๋ ๋น์ ์ ์ฉํ๋ฉด ๋๋ฒ๊น
์ด ์ด๋ ค์์ง ์ ์์ผ๋ฏ๋ก ์ค์ํ ๋น์ ์ฆ์ ์ด๊ธฐํ๋ฅผ ์ ์งํ๋ ๊ฒ ์ข์.