http://smjava.tistory.com/61 에서 좀더 이어서
★위에 주소에 있는 예제 꼭 참고!!!!
●에노테이션(annotation) 기반 생성자를 사용한 의존관계 설정 di2번 패키지를 복사해서 di8패키지를 만들어서 붙혀놓고 해보자.
di8패키지를 에노테이션 스캔 하게 태그 등록하고, Coffee클래스에 에노테이션 붙여서 빈으로 등록
스프링 설정파일
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="di8"></context:component-scan>
</beans>
Coffee 클래스
package di8;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Coffee {
private Americano americano;
@Autowired
public Coffee(Americano ame){
americano = ame;
}
public void coffeeType(){
System.out.println(americano.getName());
}
}
그리고, ice 나 hot 클래스중에 컴포넌트를 붙혀주면 Autowired가 알아서 타입이 맞는 아이를 집어넣어줌
저는 일단 ice에 컴포넌트를 달아줬어요~
package di8;
import org.springframework.stereotype.Component;
@Component
public class IceAmericano implements Americano{
public String getName(){
return"차가운 아메리카노";
}
}
Autowired는 기본적으로 타입기반의 매칭이다.
-타입맞는 빈객체가 없으면?? → NoSuchBeanDefinitionException이 발생
아예 컨테이너 자체가 안올라감
-두개 이상이면?? → NoUniqueBeanDefinitionException이 발생
아예 컨테이너 자체가 안올라감
에노테이션 생성자 버전 생성자위에 Autowired를 박는거로 의존 관계설정을 하는데 꼭 맞는애가 1개만 있어야된다.
위에서와 같이 di9패키지를 에노테이션 스캔 하게 태그 등록하고, Coffee클래스에 에노테이션 붙여서 빈으로 등록
Coffee클래스
package di9;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class Coffee {
@Autowired
private Americano americano;
// @Autowired
// @Qualifier("hotAmericano")
public void setCoffee(Americano americano){
this.americano = americano;
}
public void coffeeType(){
System.out.println(americano.getName());
}
}
위 주석된 자리에 Autowired를 넣고 Qualifier지시자에 빈 아이디(이름)을 넣어주면 그것으로 집어넣는다.
단 ice와hot에 모두 Component를 달아 놓았을때이다.
위 주석되지 않은자리에 Autowired있을때는 타입맞는 빈이 두개이상인데 Qualifier지시자를 이용해서 지목하지 않아도↓
package di9;
import org.springframework.stereotype.Component;
@Component("americano")
public class HotAmericano implements Americano{
public String getName(){
return"따듯한 아메리카노~";
}
}
위처럼 변수명이랑 같은 이름의 빈이 등록되 있다면 이것을 연결한다.
출처 : 삼성SDS멀티캠퍼스
강사 : 홍승길
Email : iccack70@gmail.com
'[Spring]' 카테고리의 다른 글
[Spring]11월 10일 Spring AOP 프록시패턴(Proxy pattern) 적용 예제 (0) | 2015.11.10 |
---|---|
[Spring]11월 10일 Spring AOP, 핵심 관심 사항, 공통 관심 사항 (0) | 2015.11.10 |
[Spring]11월 9일 초기화메소드와 소멸메소드 지정하는 방법 (0) | 2015.11.10 |
[Spring]11월 9일 스프링 설정 파일을 이용한 객체간의 의존관계 설정 (0) | 2015.11.10 |
[Spring]11월 6일 Spring 사용 기초 예제(의존성주입(DI), 제어의역행(IOC) ) (1) | 2015.11.09 |