본문 바로가기
Spring

Spring 컴포넌트스캔 component-scan

by Jann 2021. 10. 21.
728x90

Spring 컴포넌트 스캔 <context:component-scan>

Spring 컴포넌트 스캔 <component-scan>

 

컴포넌트 스캔(Component Scan)이란?


@Component 의 모든 대상을 빈에 등록하기 위해 찾는 과정으로
@Bean을 통해 하나하나 지정할 필요 없이 beans.xml 파일에 입력하면 모든 해당 파일을 인식하게 해준다.

 

beans.xml 파일에서<component-scan> 설정 예시 코드

<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

<!-- 주석 : 현재 프로젝트에서 사용되는 @을 인식할 수 있도록 요청 -->

<context:component-scan base-package="com.test" />

</beans>

 

컴포넌트 스캔(Component Scan) 특징

  • 가장 앞 문자를 소문자로 바꾼 것이 빈 이름이 된다.

  • @Component("지정할 이름") 형식으로 수동으로 지정해준다.

 

@Component("UserService") 사용 예시 코드

package com.test;

import javax.annotation.Resource;
import org.springframework.stereotype.Component;

@Component("UserService")
public class UserServiceImpl implements UserService {

		@Resource(name="myuser")
		UserVo member;
	
		@Override
		public void addUser() {
			System.out.println("추가된 멤버 :" + member.getUserName());
			
		}
}

 

 

728x90

댓글