@Component 어노테이션은 클래스를 Component로 표시하는 데 사용됩니다. 이는 Spring 프레임워크가 어노테이션 기반 구성 및 클래스 경로 스캐닝이 사용될 때 이러한 클래스를 의존성 주입을 위해 자동으로 감지한다는 것을 의미합니다.
Spring Component
간단히 말해, Component는 어떤 동작을 담당합니다. Spring 프레임워크는 클래스를 Component로 표시할 때 사용할 수 있는 세 가지 다른 특정 어노테이션을 제공합니다.
Service
: 클래스가 일부 서비스를 제공한다는 것을 나타냅니다. 유틸리티 클래스는 Service 클래스로 표시할 수 있습니다.Repository
: 이 어노테이션은 CRUD 작업을 다루는 클래스임을 나타냅니다. 보통 데이터베이스 테이블과 작업하는 DAO 구현과 함께 사용됩니다.Controller
: 대부분 웹 애플리케이션이나 REST 웹 서비스와 함께 사용되어 클래스가 프론트 컨트롤러이며 사용자 요청을 처리하고 적절한 응답을 반환하는 역할을 담당합니다.
주의하세요. 모든 이 네 가지 주석은 org.springframework.stereotype
패키지에 있으며 spring-context
jar의 일부입니다. 대부분의 경우 컴포넌트 클래스는 그 세 가지 특수화된 주석 중 하나에 속하므로 @Component
주석을 많이 사용하지 않을 수 있습니다.
Spring 컴포넌트 예제
Spring Component 주석의 사용과 Spring이 주석 기반 구성 및 클래스 경로 스캐닝으로 자동 감지하는 방법을 보여주기 위해 매우 간단한 Spring 메이븐 애플리케이션을 만들어 보겠습니다. 메이븐 프로젝트를 만들고 다음과 같은 Spring Core 의존성을 추가하세요.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
이것으로 스프링 프레임워크의 핵심 기능을 얻을 수 있습니다. 이제 간단한 컴포넌트 클래스를 만들고 @Component
주석으로 표시해 보겠습니다.
package com.journaldev.spring;
import org.springframework.stereotype.Component;
@Component
public class MathComponent {
public int add(int x, int y) {
return x + y;
}
}
이제 주석 기반 스프링 컨텍스트를 만들고 그것에서 MathComponent
빈을 가져올 수 있습니다.
package com.journaldev.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringMainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.journaldev.spring");
context.refresh();
MathComponent ms = context.getBean(MathComponent.class);
int result = ms.add(1, 2);
System.out.println("Addition of 1 and 2 = " + result);
context.close();
}
}
위의 클래스를 일반 자바 애플리케이션으로 실행하면 콘솔에 다음 출력이 표시됩니다.
Jun 05, 2018 12:49:26 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 12:49:26 IST 2018]; root of context hierarchy
Addition of 1 and 2 = 3
Jun 05, 2018 12:49:26 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 12:49:26 IST 2018]; root of context hierarchy
Spring의 힘을 느꼈나요? 우리의 컴포넌트를 스프링 컨텍스트에 주입하기 위해 아무것도 할 필요가 없었습니다. 아래 이미지는 Spring 컴포넌트 예제 프로젝트의 디렉토리 구조를 보여줍니다. 또한 컴포넌트 이름을 지정하고 동일한 이름을 사용하여 스프링 컨텍스트에서 가져올 수 있습니다.
@Component("mc")
public class MathComponent {
}
MathComponent ms = (MathComponent) context.getBean("mc");
비록 나는 @Component
주석을 MathComponent와 함께 사용했지만, 이는 사실 서비스 클래스이며 @Service
주석을 사용해야 합니다. 결과는 여전히 동일할 것입니다.
프로젝트는 GitHub 저장소에서 확인할 수 있습니다.
참고: API 문서
Source:
https://www.digitalocean.com/community/tutorials/spring-component