๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
TIL

01/26(๊ธˆ) ๋‚ด์ผ๋ฐฐ์›€์บ ํ”„ Java 25์ผ์ฐจ TIL - Bean

by ๊ฐ์ž๊ฐœ๋ฐœ๊พผ 2024. 1. 26.

 

๐Ÿ“–  ์˜ค๋Š˜์˜ ํ•™์Šต ํ‚ค์›Œ๋“œ

  • Bean

 

๐Ÿฅ”  Bean

Bean : Spring์ด ๊ด€๋ฆฌํ•˜๋Š” ๊ฐ์ฒด
Spring IoC ์ปจํ…Œ์ด๋„ˆ : 'Bean'์„ ๋ชจ์•„๋‘” ์ปจํ…Œ์ด๋„ˆ

 

 

โ—๏ธ 

Bean ๋“ฑ๋ก ๋ฐฉ๋ฒ•

 

@Component

- Bean์œผ๋กœ ๋“ฑ๋กํ•˜๊ณ ์ž ํ•˜๋Š” ํด๋ž˜์Šค ์œ„์— ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.

@Component
public class MemoService { ... }

 

Spring ์„œ๋ฒ„๊ฐ€ ๋œฐ ๋•Œ IoC ์ปจํ…Œ์ด๋„ˆ์— 'Bean'์„ ์ €์žฅํ•ด ์ค๋‹ˆ๋‹ค.

- @Component๊ฐ€ ์„ค์ •๋œ ํด๋ž˜์Šค์— ๋Œ€ํ•ด Spring์ด ํ•ด์ฃผ๋Š” ์ผ ํ™•์ธํ•˜๊ธฐ

// 1. MemoService ๊ฐ์ฒด ์ƒ์„ฑ
MemoService memoService = new MemoService();

// 2. Spring IoC ์ปจํ…Œ์ด๋„ˆ์— Bean (memoService) ์ €์žฅ
// memoService -> Spring IoC ์ปจํ…Œ์ด๋„ˆ

 

Spring Bean ์ด๋ฆ„ : ํด๋ž˜์Šค์˜ ์•ž๊ธ€์ž๋งŒ ์†Œ๋ฌธ์ž๋กœ ๋ณ€๊ฒฝ๋จ.

public class MemoService -> memoservice

 

 

๐Ÿฅ”  Spring Bean ์‚ฌ์šฉ ๋ฐฉ๋ฒ•

@Autowired

     - ํ•„๋“œ ์œ„์— @Autowired

@Component
public class MemoService {
		
    @Autowired
    private MemoRepository memoRepository;
		
		// ...
}

Spring์—์„œ IoC ์ปจํ…Œ์ด๋„ˆ์— ์ €์žฅ๋œ memoRepository 'Bean'์„ ํ•ด๋‹น ํ•„๋“œ์— DI ์ฆ‰, ์˜์กด์„ฑ์„ ์ฃผ์ž…ํ•ด ์ค๋‹ˆ๋‹ค.

 

 

 

 

๐Ÿ“š  ์˜ค๋Š˜์˜ ํšŒ๊ณ 

Bean.. ์ปคํ”ผ์ฝฉ..