@Autowired, @Qualifier 사용법
[ 이전 글 ] XML 사용법 XML 사용법 [ 이전 글 ] Inversion of Control Container ( Ioc Container ) Inversion of Control Container ( Ioc Container ) ( 이전 글과 이어지는 내용입니다. https://cloakinghost.tistory.com/8 ) 작성한 XML 파
cloakinghost.tistory.com
<context:annotation-config/>
<bean id="console" class="spring.di.ui.GridExamConsole"/>
현재까지 XML에 남아있는 내용이다
여기서 나머지 Bean도 어노테이션으로 생성되도록 해보자
<context:component-scan base-package="spring.di.ui"/>
XML에 있는 내용을 위의 한줄로 바꾸자
참고로 <context:annotation-config> 이것은 객체가 생성이 되고난 후에 어노테이션을 확인하라는 의미이다
따라서 객체를 생성하면서 해당 객체안을 확인하는 지시를 위해 위와 같이 내용을 바꾼것이다
package spring.di.ui;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import spring.di.entity.Exam;
@Component
public class GridExamConsole implements ExamConsole {
@Autowired
@Qualifier("exam2")
private Exam exam;
// 이하 생략
}
또한 @Autowired에서 required 옵션을 제거했기에 exam객체가 무조건 생성이 되야하므로 Exam 인터페이스로 구현된 클래스에도 @Component를 입력하자
package spring.di.entity;
import org.springframework.stereotype.Component;
@Component
public class ScoreExam implements Exam {
// 이하 생략
}
이제 실행부( main() )에서 2가지 선택지가 있다
ApplicationContext context = new ClassPathXmlApplicationContext("spring/di/setting.xml");
// ExamConsole console = (ExamConsole) context.getBean("console");
ExamConsole console = context.getBean(ExamConsole.class);
console.print();
GridExamConsole 클래스에 @Component가 확인되면 객체를 생성
주석 처리가 되어있는 부분에 getBean("console")로 특정 객체를 생성할 수도 있다
이럴때는 아래와 같이 @Component에 옵션은 주어야한다
@Component("console")
public class GridExamConsole implements ExamConsole {
// 이하 생략
}
728x90
'Spring' 카테고리의 다른 글
@Component 분석 ( 3 ) (0) | 2023.08.07 |
---|---|
@Component 사용법 ( 2 ) (0) | 2023.08.07 |
@Autowired, @Qualifier 사용법 (0) | 2023.08.05 |
XML 사용법 (0) | 2023.08.05 |
Inversion of Control Container ( Ioc Container ) (0) | 2023.06.14 |