스프링 어노테이션에 정리....

Dong Wook Lee (Michael)·2021년 1월 30일
0

코드숨 과제를 진행하다가, @Configuration 어노테이션을 용도에 맞지 않게 사용하지 않는다는 코드리뷰를 받았다.

생각을 해보니 그냥 인터넷에 있는 예제를 따라서 사용하기만 했지 이것이 정확이 어떤 역할을 하는지에 대해서는 공부한 적이 없었다. 따라서 이번 기회에 스프링에서 사용하는 어노테이션에 대해서 자세히 알아보기로 하였다.

코드숨 커뮤니티에서는 클래스 주석을 읽거나, 공식 문서를 활용하라는 조언이 있었기 때문에, 자료는 되도록이면 블로그에 있는 자료를 참고하지 않고, 공식 문서나 클래스에 적혀있는 주석에서 참고하였다. 물론 공식 문서를 읽는 것은 어렵지만, 언젠가는 배워야하는 것이기에 과제를 하는동안 계속 시도를 해보려고 한다.

@Configuration

스프링 공식 문서에는 이렇게 적혀 있다.

Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime, for example:

나름 해석을 해보자면, @Configuration 어노테이션은 클래스가 하나 또는 이상의 @Bean 메서드를 선언하고 스프링 컨테이너에 의해 처리되며, 런티임에 빈 정의 및 서비스 요청을 생성할 수 있다.

일단은 무슨 소리인지 이해가 잘.. 가지는 않았다. 따라서 코드에 있는 주석을 읽어보도록 하겠다.

음.. 스프링 빈 정의를 명시적으로 지정하는 것 같았다. 그리고 만약 이름을 명시적으로 지정하지 않는다면 이름은 자동적으로 생성된다고 되어 있다. 그리고 지정된 이름을 반환하는 것 같았다.

@Service

Indicates that an annotated class is a "Service", originally defined by Domain-Driven Design (Evans, 2003) as "an operation offered as an interface that stands alone in the model, with no encapsulated state."
May also indicate that a class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.
This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

이 어노테이션은 비즈니스 서비스이거나 유사한 것을 나타낼 때 사용을 한다.
따라서 코드 리뷰에서 원하시는 것이 생각에는 ServiceImpl 클래스에 @Configuration 어노테이션을 사용하는 것이 아니라, @Service 어노테이션을 사용하는 것이 적절하다는 생각이 들었다.
그리고 이 어노테이션은 @Component을 구현하고 있고 있으므로, 구현 클래스가 클래스 경로 검색을 통해서 자동으로 탐지될 수 있다.

@Component

Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.
Other class-level annotations may be considered as identifying a component as well, typically a special kind of component: e.g. the @Repository annotation or AspectJ's @Aspect annotation.

이 어노테이션은, 클래스가 '컴포넌트' 임을 나타낸다. 이러한 클래스는 클래스 패쓰 스캐닝을 할 때 자동으로 탐지된다. 예를 들어서, @Repository, @Aspect와 같은 어노테이션도 컴포넌트라는 것을 나타내는 구성 요소이다.

Controller

Indicates that an annotated class is a "Controller" (e.g. a web controller).
This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the RequestMapping annotation.

가장 간단하게도, 그저 이 클래스가 컨트롤러라는 것을 나타낸다. 이 클래스 역시 @Component 에서 파생된 어노테이션이므로 자동으로 스캐닝이 된다.

profile
오픈소스 메인테이너를 꿈꾸는 개발자!

0개의 댓글