[매일메일] @Component, @Controller, @Service, @Repository의 차이에 대해서 설명해주세요.
-
@Component, @Controller, @Service, @Repository는 각 역할에 맞는 스프링빈을 등록할 때 사용하는 어노테이션으로 스프링의 컴포넌트 스캔에 의해 자동으로 빈으로 등록된다. @Controller, @Service, @Repository는 내부적으로 @Component를 포함한다.
@Component
가장 기본적인 어노테이션으로, 특정 역할에 종속되지 않는 일반적인 스프링 빈을 나타낸다. 공통 기능을 제공하는 유틸리티 클래스나, 특정 계층에 속하지 않는 일반적인 컴포넌트를 정의할 때 사용된다.
@Service 대신 @Component를 사용하는건 가능하긴 하지만 해당 레이어의 특징(비즈니스 로직 작성)을 명시하기 위해 사용한다고 보면 된다.
@Repository 대신 @Component?
@Repository를 사용하면 PersistenceExceptionTranslationPostProcessor에 의해 예외가 공통적인 예외(DataAccessException)으로 변환된다. 만약에 @Repository를 사용하지 않으면 데이터베이스마다 예외들에 다르기 때문에 결국 데이터베이스에 종속적인 코드를 작성할 수 밖에 없다.
AOP 적용시?
@Slf4j
@Aspect
@Component
public class LoggingAspect {
@Around("@within(org.springframework.stereotype.Service)")
public Object logServiceMethods(ProceedingJoinPoint joinPoint) throws Throwable {
// 로깅 로직
}
}
@Service, @Controller, @Repository를 사용하면 각각의 계층을 뚜렷하게 구분할 수 있으므로 위와 같이 AOP를 적용할 때 유용하다. 반대로 @Component 사용시 계층 구분이 불분명해져 AOP 적용이 어려울 수 있다. 위 AOP 로깅 코드는 서비스 레이어에만 적용될 수 있도록 구현한 것이다.