Managed Components
Stereotype Annotation을 활용하여 Spring Framework의 컨테이너에 의해 관리되어야 하는 Bean들을 정의한다.
일반적으로 Parent Stereotype Annotation인
@Component
를 활용하면 모든 Bean에 대한 정의가 가능하다.
그러나 Spring Framework에서는 레이어별로 구성 요소를 구분하여 다음과 같은 Annotation을 사용할 것을 권장하고 있고,
향후 지속적으로 레이어별 특성을 반영할 수 있는 속성들을 추가해 나아갈 예정이다.
- @Service
서비스 레이어를 구성하는 대상 클래스를 정의하는데 사용한다.
- @Controller
프리젠테이션 레이어를 구성하는 Controller 클래스를 정의하는데 사용하며, SpringMVC 기반인 경우에 활용 가능하다.
- @Repository
데이터 접근 레이어를 구성하는 클래스를 정의하는데 사용하며, 퍼시스턴스 레이어에서 발생한 Exception에 대한 Translation이 지원된다.
본 문서에서는 위에서 나열한 annotation을 사용하는 방법에 대해서 자세히 살펴보도록 한다.
Auto Detecting
서비스 속성 정의 XML 내에
<context:component-scan />
을 정의함으로써 Spring 컨테이너가 Stereotype Annotation을 정의한 클래스를
자동 검색할 수 있도록 한다. <context:component-scan />을 정의한 경우 Annotation 인식을 위한 설정
<context:annotation-config/>
을
별도로 추가하지 않아도 된다.
다음은 서비스 레이어의 구성 요소인
UserServiceImpl
클래스에 대해 @Service라는 Stereotype Annotation을 사용한 예이다.
@Service
public UserServiceImpl implements UserService {
@Resource
private UserDAO userDAO;
// implements business logic
}
위 예제에서 해당 클래스의 클래스명(소문자로 시작)이 Bean name으로 셋팅되어 해당 Bean을 찾을 때
userServiceImpl
이라는 문자열을 사용해야 한다.
UserService service = (UserService)context.getBean("userServiceImpl");
해당 Annotation에 속성을 부여하면, 원하는 Bean name을 지정하는 것 또한 가능하다.
@Service("UserServiceA")
public UserServiceImpl implements UserService {
@Resource
private UserDAO userDAO;
// implements business logic
}
이 경우에 해당되는 Bean을 찾기 위해서는 속성으로 정의한 Name을 활용해야 한다.
UserService service = (UserService)context.getBean("UserServiceA");
Using Filters to customize scanning
<context:component-scan />의 여러 속성들을 이용하면 검색 대상의 범위를 조정할 수 있다.
base-package는 context:component-scan 내에 정의 가능한 속성으로 검색 대상 패키지를 정의하는 용도로 사용된다.
이외에도 context:component-scan은 하위 element로 include-filter, exclude-filter를 가질 수 있는데,
다양한 Filter Type(type)에 해당하는 표현식(expression)을 정의함으로써 이에 해당하는 클래스들을 포함 또는 제외시킬 수가 있다.
다음은 include-filter, exclude-filter 사용 예이다.
<context:component-scan base-package="com.sds.emp">
<context:include-filter type="regex" expression=".*Stub.*Repository"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
정의 가능한 Filter Type은 4가지이며, 다음과 같다.
| Filter Type
|
Example Expressions
|
| annotation
|
org.example.SomeAnnotation |
| assignable
|
org.example.SomeClass |
| regex
|
org\.example\.Default.* |
| aspectj
|
org.example..*Service+ |
※ Stereotype annotation이 적용된 클래스를 auto detection하는 기능을 사용하지 않고자 하는 경우에는 <context:component-scan />태그에
use-default-filters="false" 속성을 추가하면 된다.