12.autowired와 qualifier
Autowired와 Qualifier
어노테이션을 할 때 형식으로 찾을 것인지 이름으로 찾을 것인지 확인 해보기
1.이름으로 찾아보기
<context:annotation-config/>
<bean class ="spring.di.entity.NewlecExam" p:kor="1" p:eng="1"/>
<bean id="console" class="spring.di.ui.GridExamConsole" >
</bean>
exam1을 주고 변수명을 바꿨을 때 바인딩이 되는지 본다
spring.di.entity.NewlecExam@2034b64c
┌──────────┬──────────┐
│ total │ avg │
├──────────┼──────────┤
│ 2 │ 0.50 │
└──────────┴──────────┘
변수명을 바꿨을 때 바인딩이 되는것을 확인 할 수 있으므로 변수명으로 찾는 것은 아니다 즉 삭제해도 상관없다 따라서 변명이 아닌 형식으로 찾는 다는 것을 알 수 있다
즉
@Autowired
@Override
public void setExam(Exam exam) {
this.exam = exam;
생성하는것은 NewlecExam 이라는 것을 통해 형성하게 되고 참조할 수 있는 객체를 찾아 바인딩을 해준다
- 만약 값이 두개 라면 ???
<context:annotation-config/>
<bean class ="spring.di.entity.NewlecExam" p:kor="1" p:eng="1"/>
<bean class ="spring.di.entity.NewlecExam" p:kor="10" p:eng="20"/>
<bean id="console" class="spring.di.ui.GridExamConsole" >
</bean>
에러 발생한다
경고: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'console': Unsatisfied dependency expressed through method 'setExam' parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'spring.di.entity.Exam' available: expected single matching bean but found 2: spring.di.entity.NewlecExam#0
console가 만족 할 수 있는 depency를 찾아보려고 했으나 사용하고자하는 기대했던 것은 1개 였으나 2개가 발견 되어 에러가 발생 되었다
이때 이름을 사용한다
<context:annotation-config/>
<bean id ="exam" class ="spring.di.entity.NewlecExam" p:kor="1" p:eng="1"/>
<bean class ="spring.di.entity.NewlecExam" p:kor="1" p:eng="2"/>
<bean id="console" class="spring.di.ui.GridExamConsole" >
</bean>
spring.di.entity.NewlecExam@2034b64c
┌──────────┬──────────┐
│ total │ avg │
├──────────┼──────────┤
│ 2 │ 0.50 │
└──────────┴──────────┘
이름을 가지고 가능 하다 이름을 바꿔봐도 바인딩이 되는가?
<context:annotation-config/>
<bean id ="exam1" class ="spring.di.entity.NewlecExam" p:kor="1" p:eng="1"/>
<bean class ="spring.di.entity.NewlecExam" p:kor="1" p:eng="2"/>
<bean id="console" class="spring.di.ui.GridExamConsole" >
</bean>
에러가 발생한다
- Qualifier 사용하기
동일한 클래스를 두가지 이상의 설정을 줘야한다면 ?
<context:annotation-config/>
<bean id ="exam1" class ="spring.di.entity.NewlecExam" p:kor="1" p:eng="1"/>
<bean id ="exam2" class ="spring.di.entity.NewlecExam" p:kor="1" p:eng="2"/>
<bean id="console" class="spring.di.ui.InlineExamConsole" >
</bean>
Autowired가 무엇을 기준으로 injection을 해주는지 본다
@Autowired
@Qualifier("exam1") //exam2
@Override
public void setExam(Exam exam) {
this.exam = exam;
원하는 설정을 퀄러파이을 사용해 사용 가능하다
댓글남기기