본문 바로가기
공부/Spring

[Spring] 기본적인 @AutoWired Annotation 사용법

by 맴썰 2022. 2. 21.

@AutoWired Annotation이란?

 - 필요한 의존객체에 해당 타입의 객체를 주입시켜주는 Annotation이다.

 - AutoWired Annotation은 3가지 경우(생성자, Setter, 필드)에 사용가능한데, 이는 다음 게시물을 참고하면 된다.

https://ghcode.tistory.com/168

 AutoWired에 주입되는 객체는 Spring Container에 Bean으로 등록되어야 있어야 사용가능하다.

@Component Annotation을 이용해서 Bean을 등록하는 방법과 @Configuration과 @Bean Annotation을 이용한 방법이 있는데, @Configuration과 @Bean Annotation을 이용한 방법과 관련된 정보는 아래 글을 참고하고, 이 글에서는 @Component Annotation을 이용한 방법을 시도해볼 것이다.

https://ghcode.tistory.com/169

@Component Annotation을 클래스 위에 붙이면 Spring Framework는 이를 Bean으로 등록한다.

그리고 @Service, @Controller, @Repository Annotation은 @Component를 확장한 것으로, 동일하게 Bean을 등록할 수 있으며 각각 Spring Framework에 이 Annotation이 붙은 Class가 Service/Controller/Repository임을 알리는 역할도 수행한다.

 

Spring MVC 프로젝트를 처음 생성했을때 주어지는 HomeController내에서 AutoWired를 사용해볼 것이다.

package com.test.service;
import org.springframework.stereotype.Service;

@Service
public class ReturnHelloService {
	public String returnHello() {
		return "Hello World!";
	}
}

Service 패키지를 새로 만들고, 그 안에 간단하게 Hello world를 반환하는 함수를 가진 서비스 클래스를 하나 만들었다.

@Service Annotation을 통해 Bean으로 등록하고, Framework에 Service임을 알린다.

그리고 HomeController에서 @AutoWired Annotation을 사용해서 ReturnHelloService를 선언하고 웹 프로젝트를 서버에서 구동시키면 된다.

그럼 이러한 오류를 만날 수 있게 된다.

복잡해 보이는 오류 중 핵심은 아래에 있는 오류인데,

org.springframework.beans.factory.NoSuchBeanDefinitionException

그냥 읽어보면 사용하는 Bean의 정의가 없다는 에러인 것 같은 느낌이 든다.

 

이를 해결하기 위해서는 Component Scan이 필요한데, 이것은 빈으로 등록될 준비를 마친, 즉 @Component 및 그 하위 Annotation이 붙은 클래스들을 Scan하는 과정이다.

 

Spring MVC 프로젝트를 처음에 생성하면 src/main/webapp/WEB-INF/spring/appServlet 경로에 있는 Servlet-context.xml file을 참고하면 다음과 같다.

 

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

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="com.test.test" />
	
	
	
</beans:beans>

맨 밑에 component-scan 대상 패키지가 com.test.test 패키지 밖에 없는 것을 확인할 수 있다.

내가 생성한 서비스 패키지는 스캔 대상에서 벗어났기 때문에 오류가 발생한 것을 알 수 있다.

따라서 <context:component-scan base-package="com.test.service" /> 구문을 추가해주면 해결된다.

 

웹 프로젝트를 실행했을 때 Hello World가 출력된 것으로 보아 @AutoWired Annotation으로 의존성 주입을 시도한 객체에 정상적으로 객체가 주입되고, 정상적으로 메소드가 실행된 것을 알 수 있다.