Spring - 객체생성과 @Component

jodbsgh·2022년 4월 2일
0

🍕"Spring"

목록 보기
7/19

@Component
class InlineExamConsole
{
	@Autowired
    public void setExam(Exam exam){
    	this.exam = exam;
    }
}

////////////////////////////////////

xml)

<context:component-scan base-package="spring.di.ui"/>
<!-- 밑에 설정하지 않았지만, 패키지 경로를 알려줄테니 한 번 찾아볼래??
	거기서 클래스 중에 @Conponent를 찾아서 객체화 해라-->

<!-- <context:annotation-config/>-->
<!-- 위에 component-scan 떄문에 어차피 InlineExamConsole 클래스 전부를 읽는다.
	따라서, 이 태그가 필요가 없음-->
<bean id="exam" class="entity.NewlecExam"/>

하지만 이 방법은 주입방법을 객체 명이 아니라 타입으로 지정해줘야 한다.

ex) 
//ExamConsole console = (ExamConsole)context.getBean("console");
//위 코드는 @Component를 생성할 때 객체명을 지정하지 않았으므로 사용 물가

ExamConsole console = context.getBean(ExamConsole.class);
//사용가능

만약 이름을 부여하고 싶다면 아래와 같이 하면 된다.

@Component("console")	//객체 이름 부여
class InlineExamConsole
{
	@Autowired
    public void setExam(Exam exam){
    	this.exam = exam;
    }
}
profile
어제 보다는 내일을, 내일 보다는 오늘을 🚀

0개의 댓글