티스토리 뷰
DI예제 2
- 이클립스 사용
- DI : Dependency Injection의 약자, 의존주입
<Student>
- package com.javalec.ex;
- public class Student {
- private String name;
- private String age;
- private String gradeNum;
- private String ClassNum;
- this.name = name;
- this.age = age;
- this.gradeNum = gradeNum;
- ClassNum = classNum;
- }
- return name;
- }
- this.name = name;
- }
- return age;
- }
- this.age = age;
- }
- return gradeNum;
- }
- this.gradeNum = gradeNum;
- }
- return ClassNum;
- }
- ClassNum = classNum;
- }
- }
-> 예제1과 다르게 생성자를 만들어 필드를 초기화
(생성자에서 파라미터를 받고 있다)
<StudentInfo>
- package com.javalec.ex;
- public class StudentInfo {
- private Student student;
- public StudentInfo(Student student) {
- this.student = student;
- }
- public void getStudentInfo() {
- if(student != null) {
- }
- }
- public void setStudent(Student student) {
- this.student = student;
- }
- }
<application.xml>
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
- <bean id="student1" class="com.javalec.ex.Student">
- <constructor-arg>
- <value>홍길동</value>
- </constructor-arg>
- <constructor-arg>
- <value>13</value>
- </constructor-arg>
- <constructor-arg>
- <value>6학년</value>
- </constructor-arg>
- <constructor-arg>
- <value>20번</value>
- </constructor-arg>
- </bean>
- <bean id ="student2" class="com.javalec.ex.Student">
- <constructor-arg value = "홍길자"/>
- <constructor-arg value = "12"/>
- <constructor-arg value = "5학년"/>
- <constructor-arg value = "21번"/>
- </bean>
- <bean id="studentInfo" class="com.javalec.ex.StudentInfo">
- <constructor-arg>
- <ref bean="student1"/>
- </constructor-arg>
- </bean>
- </beans>
-> Student에서 생성자를 이용 : constructor-arg 사용
(property, value는 setter 사용할 때)
<main>
- package com.javalec.ex;
- import org.springframework.context.support.AbstractApplicationContext;
- import org.springframework.context.support.GenericXmlApplicationContext;
- public class MainClass {
- //스프링 컨테이너 구동
- String config = "classpath:application.xml";
- AbstractApplicationContext ctx = new GenericXmlApplicationContext(config); //스프링 컨테이너 형성
- //스프링 컨테이너에서 생성한 객체 요청
- StudentInfo studentInfo = ctx.getBean("studentInfo", StudentInfo.class);
- studentInfo.getStudentInfo();
- Student student2 = ctx.getBean("student2", Student.class);
- //bean에서 student2를 가져옴
- studentInfo.setStudent(student2);
- //studentInfo에 student2로 set
- studentInfo.getStudentInfo();
- //컨테이너 종료
- ctx.close();
- }
- }
<결과>
'Spring' 카테고리의 다른 글
Spring 2 (0) | 2020.10.13 |
---|---|
Spring 1 (0) | 2020.10.13 |
[Spring] DI Annotation 예제 (0) | 2018.05.13 |
[Spring] DI 기본예제 3 (0) | 2018.05.13 |
[Spring] DI 기본예제 (0) | 2018.05.13 |
댓글
최근에 올라온 글
최근에 달린 댓글
링크
- Total
- Today
- Yesterday