웹사이트 검색

스프링 @컴포넌트


Spring Component 주석은 클래스를 Component로 표시하는 데 사용됩니다. 주석 기반 구성 및 클래스 경로 스캐닝을 사용할 때 종속성 주입을 의미합니다.

스프링 컴포넌트

평신도 용어로 구성 요소는 일부 작업을 담당합니다. Spring 프레임워크는 클래스를 구성 요소로 표시할 때 사용할 세 가지 다른 특정 주석을 제공합니다.

  1. Service: 클래스가 일부 서비스를 제공함을 나타냅니다. 유틸리티 클래스는 서비스 클래스로 표시할 수 있습니다.
  2. 저장소: 이 주석은 클래스가 CRUD 작업을 처리함을 나타내며 일반적으로 데이터베이스 테이블을 처리하는 DAO 구현과 함께 사용됩니다.
  3. 컨트롤러: 클래스가 전면 컨트롤러이고 사용자 요청을 처리하고 적절한 응답을 반환하도록 지정하기 위해 주로 REST 웹 서비스와 함께 사용됩니다.

이 네 가지 주석은 모두 org.springframework.stereotype 패키지와 spring-context jar의 일부에 있습니다. 대부분의 경우 구성 요소 클래스는 세 가지 특수 주석 중 하나에 속하므로 @Component 주석을 많이 사용하지 않을 수 있습니다.

스프링 컴포넌트 예제

Spring 구성 요소 주석의 사용과 Spring이 주석 기반 구성 및 클래스 경로 스캐닝을 통해 이를 자동 감지하는 방법을 보여주기 위해 매우 간단한 Spring maven 애플리케이션을 만들어 봅시다. maven 프로젝트를 만들고 다음 스프링 코어 종속성을 추가합니다.

<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
@Component("mc")
public class MathComponent {
}
MathComponent ms = (MathComponent) context.getBean("mc");

MathComponent와 함께 @Component 주석을 사용했지만 실제로는 서비스 클래스이므로 @Service 주석을 사용해야 합니다. 결과는 여전히 동일합니다.

GitHub 리포지토리에서 프로젝트를 체크아웃할 수 있습니다.

참조: API 문서