Spring

Spring, @Component vs @Service

Mussyan 2021. 7. 16. 09:57

Component vs service

스프링에서 컴포넌트 스캔 대상임을 알리기 위한 어노테이션으로 @Component, @Service, @Controller, @Repository 등을 사용한다.

이들 간의 역할은 생각보다는 별 차이가 없다.

 

{

Spring provides further stereotype annotations: @Component, @Service, and @Controller.

@Component is a generic stereotype for any Spring-managed component.

@Repository, @Service, and @Controller are specializations of @Component for more specific use cases,

for example, in the persistence, service, and presentation layers, respectively.

Therefore, you can annotate your component classes with @Component,

but by annotating them with @Repository, @Service, or@Controller instead,

your classes are more properly suited for processing by tools or associating with aspects.

- 스프링 레퍼런스 발췌(https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-stereotype-annotations)

 

Core Technologies

In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do

docs.spring.io

}

 

요약하자면 @Service(service layer), @Controller(presentation layer), @Repository(persistance layer) 는 @Component의 역할을 수행하되 해당 클래스의 역할을 명시적으로 알려주는 느낌이다.

그래서 가능하면 역할에 따라 @Component 보다는 다른 세 가지를 사용하는 것을 권장함.

추가로 @Controller에는 @RequestMapping을 함께 사용할 수 있다는 차별점이 있다.(@Component와는 원하는 대로 동작하지 않을 수 있음.)