Spring @Service 어노테이션은 @Component 어노테이션의 특수화된 형태입니다. 스프링 서비스 어노테이션은 클래스에만 적용될 수 있습니다. 이것은 클래스를 서비스 제공자로 표시하는 데 사용됩니다.
Spring @Service 어노테이션
스프링 @Service 어노테이션은 비즈니스 기능을 제공하는 클래스와 함께 사용됩니다. 스프링 컨텍스트는 어노테이션 기반 구성 및 클래스 경로 스캔이 사용될 때 이러한 클래스를 자동으로 감지합니다.
Spring @Service 예제
간단한 스프링 애플리케이션을 만들어보겠습니다. 여기서는 스프링 서비스 클래스를 만들겠습니다. 이클립스에서 간단한 메이븐 프로젝트를 만들고 다음 스프링 코어 종속성을 추가합니다.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
최종 프로젝트 구조는 아래 이미지와 같을 것입니다. 서비스 클래스를 만들어 봅시다.
package com.journaldev.spring;
import org.springframework.stereotype.Service;
@Service("ms")
public class MathService {
public int add(int x, int y) {
return x + y;
}
public int subtract(int x, int y) {
return x - y;
}
}
주의하세요. 이것은 두 정수를 더하고 빼는 기능을 제공하는 간단한 자바 클래스입니다. 그래서 우리는 이를 서비스 제공자라고 부를 수 있습니다. @Service 주석으로 이를 주석 처리했으므로 스프링 컨텍스트가 이를 자동으로 감지하고 우리가 컨텍스트에서 인스턴스를 가져올 수 있도록 할 수 있습니다. 메인 클래스를 만들어 보겠습니다. 여기서는 주석 기반의 스프링 컨텍스트를 생성하고 서비스 클래스의 인스턴스를 가져올 것입니다.
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();
MathService ms = context.getBean(MathService.class);
int add = ms.add(1, 2);
System.out.println("Addition of 1 and 2 = " + add);
int subtract = ms.subtract(2, 1);
System.out.println("Subtraction of 2 and 1 = " + subtract);
// 스프링 컨텍스트 닫기
context.close();
}
}
자바 애플리케이션으로 클래스를 실행하면 다음 출력이 생성됩니다.
Jun 05, 2018 3:02:05 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 15:02:05 IST 2018]; root of context hierarchy
Addition of 1 and 2 = 3
Subtraction of 2 and 1 = 1
Jun 05, 2018 3:02:05 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 15:02:05 IST 2018]; root of context hierarchy
MathService 클래스를 주의하면 서비스 이름을 “ms”로 정의했습니다. 이 이름을 사용하여 MathService
의 인스턴스를 가져올 수도 있습니다. 이 경우 출력은 동일하게 유지됩니다. 그러나 명시적 캐스팅을 사용해야 합니다.
MathService ms = (MathService) context.getBean("ms");
이것이 스프링 @Service 주석의 빠른 예제입니다.
예제 프로젝트 코드는 GitHub Repository에서 다운로드할 수 있습니다.
참고: API 문서
Source:
https://www.digitalocean.com/community/tutorials/spring-service-annotation