본문 바로가기

Java

[Spring / JAVA] 의존성 주입 DI (Dependency Injection)

의존성 주입 이란??

 

의존성 주입(Dependency Injection, DI)은 객체 지향 프로그래밍에서 의존성 관리를 위한 기법 중 하나입니다. 이 기법은 클래스 간의 결합도를 낮추고, 모듈 간의 독립성을 높이며, 코드 테스트 용이성을 증가시키는 등의 장점을 가지고 있습니다.

 

 

소스코드를 보면서 이해해봅시다.

 

우선 Spring Project를 생성한 후 src/main/java 폴더 아래에 Family, MainClass, Student, StudentInfo 클래스를 만들어 줍시다. 그리고 resource폴더 아래에 applicationCTX3.xml, applicationCTX4.xml 파일을 만들어 줍니다. 

Student.java

package com.bit.se2;

import java.util.ArrayList;

public class Student {
	private String name;
	private ArrayList<String> hobbys;
	
	public Student(String name,ArrayList<String> hobbys) {
		this.name=name;
		this.hobbys=hobbys;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public ArrayList<String> getHobbys() {
		return hobbys;
	}

	public void setHobbys(ArrayList<String> hobbys) {
		this.hobbys = hobbys;
	}
}

 

 

StudentInfo.java

package com.bit.se2;

public class StudentInfo {
	
	private Student student;
	
	public StudentInfo(Student student) {
		this.student=student;
	}
	
	public Student getStudentInfo() {
		if(student != null) {
			System.out.println("이름 : "+student.getName());
			System.out.println("취미 : "+student.getHobbys());
			System.out.println("=====================");
		}
		return student;
	}
	
	public StudentInfo() {

	}
	
	public void setStudent(Student student) {
		this.student=student;
	}
	
	public Student getStudent() {
		return student;
	}
}

 

 

Family.java

package com.bit.se2;

public class Family {
	String papaName;
	String mamiName;
	String sisterName;
	String brotherName;
	
	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 클래스에는 String 타입의 name, ArrayList 타입의 hobbys 필드를 생성하고

StudentInfo 클래스는 생성자와 이름과 취미를 출력하는 메서드인 getStudentInfo를 작성해줍니다.

Family 클래스는 아빠,엄마,여동생,남동생 이름을 저장하는 변수를 생성해주고 setter,getter를 통해 값을 저장하고 주고받도록 작성해 줍시다.

 

Main 클래스를 살펴봅시다

 

MainClass.java

package com.bit.se2;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class MainClass {

	public static void main(String[] args) {
		
		String configLocation1 = "classpath:applicationCTX3.xml";
		String configLocation2 = "classpath:applicationCTX4.xml";
		AbstractApplicationContext ctx = new GenericXmlApplicationContext(configLocation1, configLocation2);
		
		Student student1 = ctx.getBean("student1", Student.class); //beans를 얻어와라
		System.out.println(student1.getName());	//홍길동
		System.out.println(student1.getHobbys());	// 수영, 요리
		
		StudentInfo studentInfo = ctx.getBean("studentInfo", StudentInfo.class);
		Student student2 = studentInfo.getStudentInfo();	//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();
		
	}
	
}

String configLocation1 = "classpath:applicationCTX3.xml";
String configLocation2 = "classpath:applicationCTX4.xml";
AbstractApplicationContext ctx = new GenericXmlApplicationContext(configLocation1, configLocation2);
를 통해 의존성을 주입하고 객체를 생성할 수 있도록 해줍니다.

 

xml파일에 정의된 student1이라는 bean를 가져와서 student1이라는 이름으로 값을 저장해줍니다.

그리고 StudentInfo라는 bean을 가져와서 studentInfo에 저장한 후 getStudentInfo 메서드를 통해 student2에 값을 할당하도록 합시다. 이때 student1과 student2가 같으면 "student1==student2"를 출력하게 됩니다. 

 

마찬가지로 student3도 생성해주고 student1과 student3을 비교해서 같으면 "student1 == student3" 을 출력하고 같지 않으면 "student1 != student3" 을 출력해주도록 작성해줍시다

 

마지막으로 family라는 bean을 가져와서 엄마,아빠,여동생,남동생의 이름을 출력합니다.

 

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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="student1" class="com.bit.se2.Student">
		<constructor-arg value="홍길동"/>
		<constructor-arg>
			<list>
				<value>수영</value>
				<value>요리</value>	
			</list>
		</constructor-arg>
	</bean>
	
	<bean id="studentInfo" class="com.bit.se2.StudentInfo">
		<constructor-arg>
			<ref bean ="student1"/>
		</constructor-arg>
	</bean>
	
	
	<bean id="student3" class="com.bit.se2.Student">
		<constructor-arg value="홍길동"/>
			<constructor-arg>
			<list>
				<value>수영</value>
				<value>요리</value>	
			</list>
		</constructor-arg>
	</bean>


</beans>

 

 

ApplicationCTX4.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:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="family" class="com.bit.se2.Family" c:papaName="강아빠" c:mamiName="강엄마" p:sisterName="강누나" p:brotherName="강형">
		<!--<constructor-arg value="강아빠"/>
		<constructor-arg value="강엄마"/>
		<property name="sisterName" value="강누나"/>
		 <property name="brotherName" value="강형"/>	 -->
	</bean>



</beans>

 여기에서 주의해야 할 점은 Family 클래스에 정의된 생성자를 살펴보면 아빠이름과 엄마이름만 값을 초기화 해주고 있는 것을 확인할 수 있는데요 그렇기 때문에 아빠,엄마 이름은 <Constructor-arg> 태그를 통해 값을 저장하고 여동생과 남동생 이름은 <property> 태그를 통해서 값을 저장해주어야 합니다.

<constructor-arg value="강아빠"/>
<constructor-arg value="강엄마"/>
<property name="sisterName" value="강누나"/>
<property name="brotherName" value="강형"/>

이렇게 작성해도 되고 코드가 길어지는게 싫다면 

<bean id="family" class="com.bit.se2.Family" c:papaName="강아빠" c:mamiName="강엄마" p:sisterName="강누나" p:brotherName="강형">

이런식으로 NameSpace를 이용해서 한줄에 출력하는 방법도 있습니다.


값이 잘 출력되는 것을 확인할 수 있습니다!

 

 

Spring에서 사용하는 의존성 주입을 포스팅 해봤습니다. 

감사합니다

 

 

'Java' 카테고리의 다른 글

[Java] 배열 복사 (Shallow Copy, Deep Copy)  (2) 2024.05.31
[Project] 영화 데이터베이스 웹 페이지 제작 ( 1 )  (0) 2024.05.31
MVC Pattern  (0) 2023.10.23
JSTL  (1) 2023.10.17