Annotation(Context Namespace)을 이용하는 방법
Context Namespace를 이용하기 위해서는 아래와 같이 applicationContext.xml 파일에 추가작성이 필요하다.
1. @Component
- @Component Annotation을 이용하면 해당 클래스의 객체를 Bean으로 등록가능
2. @Autowired
- 특정 객체의 멤버변수에 의존성 주입
- 생성자나 메소드, 멤버변수 위에 사용가능
- 보통 멤버변수위에 사용
/* 변수 위에 사용 */
@Component("tv1")
public class SamsungTV implements TV{
@Autowired
private Speaker speaker;
}
/* 생성자 위에 사용 */
@Component("tv1")
public class SamsungTV implements TV{
private Speaker speaker;
@Autowired
public SamsungTV(Speaker speaker){
this.speaker = speaker;
}
}
/* 메소드 위에 사용 */
@Component("tv1")
public class SamsungTV implements TV{
private Speaker speaker;
@Autowired
public void initSamsungTV(Speaker speaker){
this.speaker = speaker;
}
}
*동작원리
1) 스프링 컨테이너가 변수 위의 @Autowired를 확인하는 순간, 해당 변수의 타입을 체크
2) 1)의 변수에 넣는 대상이 객체일 경우, 해당 객체가 메모리에 존재하는지 확인 후, 그 객체를 변수에 주입한다.
3) 만약 해당 객체가 없다면 NoSuchBeanDefinitionException을 발생시킨다.
3. @Qualifier
- 만약, 동일한 타입의 객체가 2개 이상일 경우, 어떤 객체를 주입할 것인지 지정이 필요하다.
- @Quailifier Annotation으로 지정이 가능하다.
- 주입할 객체와 같은 타입의 객체를 찾은 다음 @Qualifier Annotation에 있는 이름으로 객체를 찾는다.
- 동일한 객체가 2개 이상인 상황에서 @Qualifier Annotation으로 주입할 객체를 지정하지 않으면 , NoUniqueBeanDefinitionException이 발생한다.
4. @Inject
- Autowired와 같은 기능을 가진다.
- 주입할 객체를 지정할 때는 @Named Annotation을 사용한다.
- 주입할 객체와 같은 타입의 객체를 찾은 다음 @Named Annotation에 있는 이름으로 객체를 찾는다.
- 해당 이름을 가진 객체가 없을 경우 타입을 기준으로 주입할 객체를 찾는다.
5. @Resource
- @Autowired와 @Qualifier의 기능을 결합한 Annotation
- 객체의 이름을 이용하여 의존성 주입 처리
'Spring > Spring Framework' 카테고리의 다른 글
@ModelAttribute와 @RequestBody의 차이점 (0) | 2022.09.29 |
---|---|
AJAX로 복잡한 JSON 객체 타입을 DTO로 받는 방법 (0) | 2022.09.27 |
[Spring 기본개념] Dependency Lookup과 Dependency Injection (Dependency Injection 편) ① (0) | 2022.02.06 |
[Spring 기본개념] Dependency Lookup과 Dependency Injection (Dependency Lookup 편) ② (0) | 2022.02.05 |
개발환경 (0) | 2022.01.23 |
댓글