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

Spring/Spring Quick Start

@Component ์‚ฌ์šฉ๋ฒ•

์Šคํ”„๋ง ์ปจํ…Œ์ด๋„ˆ๋Š”

ํด๋ž˜์Šค ํŒจ์Šค์— ์žˆ๋Š” ํด๋ž˜์Šค๋“ค์„ ์Šค์บ”ํ•˜์—ฌ

@Component๊ฐ€ ์„ค์ •๋œ ํด๋ž˜์Šค๋“ค์„ ์ž๋™์œผ๋กœ ๊ฐ์ฒด ์ƒ์„ฑํ•œ๋‹ค.

 

์–ด๋…ธํ…Œ์ด์…˜ ์„ค์ •ํ•˜๋Š” ๋ฐฉ๋ฒ•

 

1. Context ๋„ค์ž„์ŠคํŽ˜์ด์Šค ์ถ”๊ฐ€

<context:component-scan/> ์—˜๋ฆฌ๋จผํŠธ๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ์ด๋‹ค.

2. ์ปดํฌ๋„ŒํŠธ ์Šค์บ”(component-scan) ์„ค์ •

<context:component-scan/> ์—˜๋ฆฌ๋จผํŠธ์˜ base-package๋กœ ์ง€์ •ํ•œ ํŒจํ‚ค์ง€๋กœ

์‹œ์ž‘ํ•˜๋Š” ๋ชจ๋“  ํŒจํ‚ค์ง€๊ฐ€ ์Šค์บ” ๋Œ€์ƒ์— ํฌํ•จ๋œ๋‹ค.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
    			http://www.springframework.org/schema/beans/spring-beans.xsd
				http://www.springframework.org/schema/context 
        		http://www.springframework.org/schema/context/spring-context-4.2.xsd">

	<context:component-scan base-package="polymorphism"></context:component-scan>
	
</beans>

3. ๊ฐ์ฒด ์ƒ์„ฑ์„ ์›Œํ•˜๋Š” ํด๋ž˜์Šค์— @Component์œผ๋กœ ์ง€์ •

๊ธฐ๋ณธ ์ƒ์„ฑ์ž๊ฐ€ ์žˆ์–ด์•ผ๋งŒ ์ปจํ…Œ์ด๋„ˆ๊ฐ€ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

package polymorphism;

import org.springframework.stereotype.Component;

@Component
public class LgTV implements TV {

	public LgTV() {
		System.out.println("===> LgTV ๊ฐ์ฒด ์ƒ์„ฑ");
	}

	// ๋ฉ”์„œ๋“œ ์ƒ๋žต
}

๋งŒ์•ฝ ํด๋ผ์ด์–ธํŠธ ํ”„๋กœ๊ทธ๋žจ์—์„œ ์Šคํ”„๋ง ์ปจํ…Œ์ด๋„ˆ๊ฐ€ ์ƒ์„ฑํ•œ ๊ฐ์ฒด๋ฅผ ์š”์ฒญํ•˜๊ธฐ ์œ„ํ•ด์„ ,

๋ฐ˜๋“œ์‹œ ์‚ฌ์šฉํ•  id๋‚˜ name์ด ์„ค์ •๋˜์–ด ์žˆ์–ด์•ผ ํ•œ๋‹ค.

package polymorphism;

import org.springframework.stereotype.Component;

@Component("tv")
public class LgTV implements TV {

	public LgTV() {
		System.out.println("===> LgTV ๊ฐ์ฒด ์ƒ์„ฑ");
	}

	// ๋ฉ”์„œ๋“œ ์ƒ๋žต
}

id๋‚˜ name ์†์„ฑ ๋ฏธ์ง€์ • ์‹œ, ์Šคํ”„๋ง ์ปจํ…Œ์ด๋„ˆ๊ฐ€ ์ž๋™์œผ๋กœ ํด๋ž˜์Šค ์ด๋ฆ„์˜ ์ฒซ ๊ธ€์ž๋ฅผ ์†Œ๋ฌธ์ž๋กœ ๋ณ€๊ฒฝํ•œ ์ด๋ฆ„์œผ๋กœ ์„ค์ •ํ•ด์ค€๋‹ค.