[spring] 객체 주입 ( DI ) 사용 예제#1
1. Student - 학생에 대한 모든 정보를 가진 클래스 2. StudentInfo - Student 클래스 객체를 가지고 있는 클래스 3. Family - 가족 정보가 들어있는 클래스 4. MainClass - 메인(실행) 클래스 위의 4개의 클래스와 xml(bean)파일로 학생의 정보를 출력하는 코드를 작성해보았습니다. |
Student
package com.javalec.ex03;
import java.util.ArrayList;
public class Student {
private String name;
private int age;
private ArrayList<String> hobbys;
private double height;
private double weight;
public Student() {}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public ArrayList<String> getHobbys() {
return hobbys;
}
public void setHobbys(ArrayList<String> hobbys) {
this.hobbys = hobbys;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}
Student 클래스는 필드와 get/setter로 구성되어있고 생성자가 있다면 setter는 없어도 되지만 생성자에 값을 넣는방법과 setter에 값을 넣는 방법 둘다 사용을 해보기 위해 둘다 만들어주었습니다. 필드에는 이름,나이,취미,신장,체중의 정보가 들어있고 생성자에는 이름,나이,취미만 매개변수로 받습니다.
Family
package com.javalec.ex03;
public class Family {
String papaName;
String mamiName;
String sisterName;
String brotherName;
public Family() {}
public Family(String papaName, String mamiName) {
this.papaName = papaName;
this.mamiName = mamiName;
}
public String getPapaName() {
return papaName;
}
public void setPapaName(String papaName) {
this.papaName = papaName;
}
public String getMamiName() {
return mamiName;
}
public void setMamiName(String mamiName) {
this.mamiName = mamiName;
}
public String getSisterName() {
return sisterName;
}
public void setSisterName(String sisterName) {
this.sisterName = sisterName;
}
public String getBrotherName() {
return brotherName;
}
public void setBrotherName(String brotherName) {
this.brotherName = brotherName;
}
}
Family클래스는 아빠,엄마,누나,형의 이름을 담아주는 4가지의 필드가 있고 생성자에는 아빠/엄마의 정보만 담도록 했습니다.
StudentInfo
package com.javalec.ex03;
public class StudentInfo {
private Student student;
public StudentInfo() {
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
StudentInfo 클래스에는 Student클래스 객체 자체를 담아주는 setter가 있고 Student필드에 그 객체를 담아줍니다.
그럼 이제 xml 파일에서 Student, Family, StudentInfo에 객체, 속성(필드) 값을 주입하는 방법을 보겠습니다.
applicationCTX2.xml
1. Student클래스에 값 주입하는 부분
<bean id="student1" class="com.javalec.ex03.Student">
<constructor-arg>
<value>홍길동</value>
</constructor-arg>
<constructor-arg>
<value>20</value>
</constructor-arg>
<constructor-arg>
<list>
<value>밥</value>
<value>잠</value>
</list>
</constructor-arg>
<property name="height">
<value>180</value>
</property>
<property name="weight">
<value>80</value>
</property>
</bean>
<bean>
태그 안에 id는 키값 이라고 생각하면 됩니다. 나중에 MainClass에서 저 id를 가지고 Student클래스의 값을 가져옵니다.
<constructor-arg> ~~ </constructor-arg>
생성자에 값을 넣는태그입니다. 순서대로 값이 입력됩니다.
<value> ~~ </value>
태그안에 작성한 값이 입력되게 됩니다.
ArrayList나 List를 쓸때는 <list></list>태그로 <value> 태그를 감싸주고 <value>를 여러개 사용할 수 있습니다.
<property> ~~ </property>
필드에 값을 넣는 태그입니다. 무조건 필드명과 똑같이 사용해주어야 하고 내부에서 자동으로 setter에 값을 넣어주게됩니다.
정리를 해보자면 Student클래스의 생성자에는 name,age,hobbys의 값을 매개변수로 받고
height,weight는 setter로 값을 전달받아 필드에 값을 넣어주게 됩니다.
위의 코드를 네임스페이스라는것을 사용하여 간결하게 표현할 수 있습니다.
네임스페이스
<!-- 네임스페이스 -->
<bean id="student1" class="com.javalec.ex03.Student"
c:name="홍길자" c:age="10" p:height="100" p:weight="40">
<property name="hobbys">
<list>
<value>밥</value>
<value>잠</value>
</list>
</property>
</bean>
<bean>태그 내의 c는 생성자(constructor) p는 속성(property)를 의미하고 그 뒤에 필드명과 똑같이 적어주면 됩니다.
List는 표현할 수 없기 때문에 따로 빼서 사용해주어야 합니다.
근데 네임스페이스를 사용하고 싶으면 설정을 해주어야합니다.
xml파일을 들어가면 밑에 sorce | Namespace | Overview | beans 라고 탭이 보일텐데 Namespace탭에서
위의 빨간박스를 체크해주면 됩니다.
2. StudentInfo에 객체주입
<bean id="studentInfo" class="com.javalec.ex03.StudentInfo">
<property name="student">
<ref bean="student1" />
</property>
</bean>
StudentInfo 클래스를 보면 Student타입의 student필드가 하나 있는데 student필드에 id: student1에 값을 주입해놓은 객체 자체를 담아주게 됩니다.
applicationCTX3.xml
1. Family에 객체(값)주입
<bean id="family" class="com.javalec.ex03.Family"
c:papaName="홍아빠" c:mamiName="홍엄마"
p:sisterName="홍누나" p:brotherName="홍오빠"/>
네임스페이스로 생성자에 papaName,mamiName , 필드에 sister/brotherName 값을 넣어줍니다.
2. Student 클래스에 두번째 객체 주입
<bean id="student3" class="com.javalec.ex03.Student"
p:name="홍길동3" p:age="20" p:height="180" p:weight="80">
<property name="hobbys">
<list>
<value>밥</value>
<value>잠</value>
</list>
</property>
</bean>
이번엔 student3 이라는 id로 applicationCTX3.xml에 값을 넣는 부분입니다. CTX2랑 다른 값을 넣어주었습니다.
MainClass
1. MainClass 전체
package com.javalec.ex03;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
String configLocation1 = "classpath:applicationCTX2.xml";
String configLocation2 = "classpath:applicationCTX3.xml";
AbstractApplicationContext ctx
= new GenericXmlApplicationContext(configLocation1, configLocation2);
Student student1 = ctx.getBean("student1", Student.class);
System.out.println(student1.getName()); //홍길동
System.out.println(student1.getHobbys()); // 수영, 요리
System.out.println(student1.getHeight());
StudentInfo studentInfo = ctx.getBean("studentInfo", StudentInfo.class);
Student student2 = studentInfo.getStudent(); //student1 == student2
System.out.println(student2.getName()); //홍길동
System.out.println(student2.getHobbys()); // 수영, 요리
if(student1.equals(student2)) {
System.out.println("student1 == student2");
}
Student student3 = ctx.getBean("student3", Student.class);
System.out.println(student3.getName());
if(student1.equals(student3)) {
System.out.println("student1 == student3");
} else {
System.out.println("student1 != student3");
}
Family family = ctx.getBean("family", Family.class);
System.out.println(family.getPapaName());
System.out.println(family.getMamiName());
System.out.println(family.getSisterName());
System.out.println(family.getBrotherName());
ctx.close();
}
}
2. MainClass에 빈즈(xml파일) 연결 하는 부분
String configLocation1 = "classpath:applicationCTX2.xml";
String configLocation2 = "classpath:applicationCTX3.xml";
AbstractApplicationContext ctx
= new GenericXmlApplicationContext(configLocation1, configLocation2);
configLocation1,2 에 xml파일을 각각 담아주고 Abstract~~ ctx = new Generic~~ ( 변수1 (xml파일경로), 변수2(xml파일경로) 를 써주면 빈즈와 연결이 되고 xml 파일에 명시해둔 클래스의 setter에 값이 담아집니다.
3. MainClass에 값을 가져와서 출력하는 부분
Student student1 = ctx.getBean("student1", Student.class);
System.out.println(student1.getName()); //홍길동
System.out.println(student1.getHobbys()); // 수영, 요리
System.out.println(student1.getHeight());
StudentInfo studentInfo = ctx.getBean("studentInfo", StudentInfo.class);
Student student2 = studentInfo.getStudent(); //student1 == student2
System.out.println(student2.getName()); //홍길동
System.out.println(student2.getHobbys()); // 수영, 요리
if(student1.equals(student2)) {
System.out.println("student1 == student2");
}
첫줄부터 보면 ctx.getBean() 메소드에서 applicationCTX2.xml 에서 <bean id="student1" 이라고 써둔 id값을 가져옵니다. 그리고 뒤에 원본 class를 명시를 해줍니다.
그러면 Student 타입의 student1이라는 래퍼런스 변수를 통해 빈즈에 저장된 값을 불러올 수 있습니다.
println으로 값이 잘 불러와지나 확인하면 잘 나오는것을 확인할 수 있습니다.
StudentInfo에는 필드에 student가 있고 그 필드에 Student 객체 자체를 담아주었습니다.
그리고 Student student2 = studentInfo.getStudent(); 명령어로 student객체를 student2에 담아줍니다.
그렇게해서 값을 얻어오고 두 객체는 같은 객체인지 확인하기 위해 if문으로 비교를 해보면 같은 객체라는것을 알 수 있습니다.
family와 student3도 동일한 방법으로 진행됩니다.
실행화면
전체코드
패키지
com.javalec.ex03
클래스
Family
package com.javalec.ex03;
public class Family {
String papaName;
String mamiName;
String sisterName;
String brotherName;
public Family() {}
public Family(String papaName, String mamiName) {
this.papaName = papaName;
this.mamiName = mamiName;
}
public String getPapaName() {
return papaName;
}
public void setPapaName(String papaName) {
this.papaName = papaName;
}
public String getMamiName() {
return mamiName;
}
public void setMamiName(String mamiName) {
this.mamiName = mamiName;
}
public String getSisterName() {
return sisterName;
}
public void setSisterName(String sisterName) {
this.sisterName = sisterName;
}
public String getBrotherName() {
return brotherName;
}
public void setBrotherName(String brotherName) {
this.brotherName = brotherName;
}
}
Student
package com.javalec.ex03;
import java.util.ArrayList;
public class Student {
private String name;
private int age;
private ArrayList<String> hobbys;
private double height;
private double weight;
public Student() {}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public ArrayList<String> getHobbys() {
return hobbys;
}
public void setHobbys(ArrayList<String> hobbys) {
this.hobbys = hobbys;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}
StudentInfo
package com.javalec.ex03;
public class StudentInfo {
private Student student;
public StudentInfo() {
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
MainClass
package com.javalec.ex03;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
String configLocation1 = "classpath:applicationCTX2.xml";
String configLocation2 = "classpath:applicationCTX3.xml";
AbstractApplicationContext ctx
= new GenericXmlApplicationContext(configLocation1, configLocation2);
Student student1 = ctx.getBean("student1", Student.class);
System.out.println(student1.getName()); //홍길동
System.out.println(student1.getHobbys()); // 수영, 요리
System.out.println(student1.getHeight());
StudentInfo studentInfo = ctx.getBean("studentInfo", StudentInfo.class);
Student student2 = studentInfo.getStudent(); //student1 == student2
System.out.println(student2.getName()); //홍길동
System.out.println(student2.getHobbys()); // 수영, 요리
if(student1.equals(student2)) {
System.out.println("student1 == student2");
}
Student student3 = ctx.getBean("student3", Student.class);
System.out.println(student3.getName());
if(student1.equals(student3)) {
System.out.println("student1 == student3");
} else {
System.out.println("student1 != student3");
}
Family family = ctx.getBean("family", Family.class);
System.out.println(family.getPapaName());
System.out.println(family.getMamiName());
System.out.println(family.getSisterName());
System.out.println(family.getBrotherName());
ctx.close();
}
}
xml(bean)
applicationCTX2.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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="studentInfo" class="com.javalec.ex03.StudentInfo">
<property name="student">
<ref bean="student1" />
</property>
</bean>
<!-- 네임스페이스 -->
<bean id="student1" class="com.javalec.ex03.Student"
p:name="홍길자" p:age="10" p:height="100" p:weight="40">
<property name="hobbys">
<list>
<value>밥</value>
<value>잠</value>
</list>
</property>
</bean>
</beans>
applicationCTX3.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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 네임스페이스 사용 하단바에서 추가해줘야함 c:생성자 p:속성 -->
<bean id="family" class="com.javalec.ex03.Family" c:papaName="홍아빠"
c:mamiName="홍엄마" p:sisterName="홍누나" p:brotherName="홍오빠" />
<bean id="student3" class="com.javalec.ex03.Student" p:name="홍길동3"
p:age="20" p:height="180" p:weight="80">
<property name="hobbys">
<list>
<value>밥</value>
<value>잠</value>
</list>
</property>
</bean>
</beans>