스프링
[Spring] AppicationContext, XML Configuration 예제
Awdsd
2020. 4. 2. 17:07
반응형
1. ApplicationContext
- 어플리케이션에 설정 정보를 전달하기 위한 Spring 인터페이스
- BeanFactory 기능을 한다 (Bean = 자바 객체) 즉, 자바 객체를 모아두는 컨테이너
- IoC(Inversion of Control) 컨테이너, Spring 컨테이너 라고도 불림
- 한마디로, 스프링에서 자바 객체를 관리하는 녀석
2. XML Configuration
- Bean 선언을 XML파일을 통해 선언
- ApplicationContext가 XML 파일을 통해 bean을 관리
3. 예제
public class NewlecExam implements Exam {
private int kor;
private int eng;
private int math;
private int com;
public NewlecExam(int kor, int eng, int math, int com) {
this.kor = kor;
this.eng = eng;
this.math = math;
this.com = com;
}
//이하 getter setter 생략
}
//bean 변수에 값 설정 방법
<bean id="exam" class="spring.di.entity.NewlecExam">
<property name="kor" value="10" />
<property name="eng" value="10" />
<property name="math" value="10" />
<property name="com" value="10" />
</bean>
//bean 생성자를 통한 정의 방법
//<constructor-arg>태그를 통해 NewlecExam 클래스의 인자 있는 생성자에 맞게 value 값이 저장됨
//index는 인자 순사
//name은 인자 이름
<bean id="exam" class="spring.di.entity.NewlecExam">
//방법 1
<constructor-arg index="0" value="30"/>
<constructor-arg index="3" value="20"/>
<constructor-arg index="1" value="10"/>
<constructor-arg index="2" value="0"/>
</bean>
<bean id="exam" class="spring.di.entity.NewlecExam">
//방법 2
<constructor-arg name="kor" type="int" value="30"/>
<constructor-arg name="eng" type="int" value="20"/>
<constructor-arg name="com" type="int" value="10"/>
<constructor-arg name="math" type="int" value="0"/>
</bean>
<bean id="exam" class="spring.di.entity.NewlecExam">
//방법 3
<constructor-arg name="kor" value="30"/>
<constructor-arg name="eng" value="20"/>
<constructor-arg name="com" value="10"/>
<constructor-arg name="math" value="0"/>
</bean>
public class Program {
public static void main(String[] args) {
//XML 파일 이름으로 ApplicationContext 컨테이너 지정
ApplicationContext context =
new ClassPathXmlApplicationContext("spring/di/setting.xml");
//XML에 지정한 Exam 클래스를 상속받은 NewlecExam 객체를 가져옴
방법 1 클래스 지정
Exam exam = context.getBean(Exam.class);
방법 2 id 지정
Exam exam = (NewlecExam)context.getBean("exam");
ExamConsole console = context.getBean(ExamConsole.class);
console.print();
}
}
참고
https://www.youtube.com/watch?v=9iNvs7aeeDM&list=PLq8wAnVUcTFUHYMzoV2RoFoY2HDTKru3T&index=9
반응형