DI(Dependency Injection)란?
직역하면 "의존성 주입"이라는 표현을 할 수 있지만, 이는 개념을 이해하기에 좋지 못한 표현이다. Spring에서 사용하는 뜻에 맞게 의역하면 "의존성있는 객체는 외부에서 주입하는 것"이라고 표현할 수 있다.
public class FryPan{
public void boil(){
System.out.println("불을 이용해 요리합니다.");
}
}
public class Cook{
FryPan fryPan;
public void init(){
fryPan = new FryPane();
}
public static void main(String[]agrs){
fryPan.boid();
}
}
예를 들어 위와 같은 코드보면, Cook클래스은 FryPan클래스의 의존하고 있는 상태이다.
위와 같이 의존성이 강한 상태에서 fryPan의 인스턴스를 생성하기 위해서 new연산자를 이용할 수 밖에 없다.
이는 FryPan을 다른 클래스로 바꿔야한다는 상황이 올 때 직접 Cook코드를 열어 바꿔줘야한다.
-> 코드가 길어지고 복잡해지면 유지보수가 까다롭다.
public inteface Pan{
public void boil();
}
public class FryPan implements Pan{
@Override
public void boil(){
System.out.println("불로 요리를 합니다");
}
}
public class Cook{
Pan pan;
public void setPan(Pan pan){
this.pan = pan;
}
public static void main(String[]agrs){
fryPan.boid();
}
}
위와 같이 인터페이스를 이용하여 코드의 결합도를 낮춰주고 좀더 유연하게 할 수 있다.
그리고 여기서 Spring은 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">
<!-- 앞으로, 소스코드에서 new하지말고, 이 xml설정파일에서 사용할 객체를 명시하면 된다...
, 스프링의 ApplicationContext가 알아서 메모리에 인스턴스를 생성하고, 주입까지 해준다!!
단, 주입받으려는 객체는 setter나 생성자가 명시되어 있어야 스프링이 주입을 할 수 있다.-->
<!-- 프라이팬을 선언 -->
<!-- 하나의 컴포넌트 = bean -->
<bean id="friPan" class="food.FriPan"/>
<bean id="cook" class="food.Cook">
<!-- cook내의 pan을 주입
cook내의 setter메서드 호출-->
<property name="pan" ref="friPan"/>
</bean>
</beans>
package food;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UseCook {
public static void main(String[] args) {
/*DI (Dependency Injection)
: 직역 시, 의존성 주입..
의역 시, 의존성있는 객체는 외부에서 주입받자!!!!
*/
//스프링을 이용하지 않고 구현한 예
//팬을 올리자
/*
* FriPan pan = new FriPan(); Cook cook = new Cook();
*
* cook.setPan(pan);//팬을 요리사에게 주입시키자!!
*
* cook.makeFood();
*/
//스프링을 이용해서 객체를 주입시켜본다..
//xml에 원하는 객체를 명시하면, 이 객체가 작성된 xml을 파악하여
//객체들의 인스턴스를 생성관리해준다.. 이러한 역할을 수행하는 객체를 가리켜
//Spring Context 객체라 한다!!!!! (외부파일을 통해 인스턴스 관리)
ClassPathXmlApplicationContext context = null; //스프링xml 설정파일을 읽어서 작성된
//객체의 인스터는스를 생성 및 관리해준다(주입도 해줌)
//외부조립자(Assembler)
context = new ClassPathXmlApplicationContext("spring/config/context.xml");
//xml이 이미 읽혀진 상태이므로, 메모리에는 인스턴스들이 존재할 것이고, 그 중 어떤 인스턴스를 가져올지는
//getBean메서드로 가져오면 된다..
Cook cook = (Cook)context.getBean("cook");
cook.makeFood();
}
}
ClassPathXmlApplication객체를 이용하여 인스턴스를 생성할 xml을 지정하여 사용할 수 있다.
스프링을 사용하면 외부파일인 XML로 코드를 유지보수할 수 있고 코드의 결합도를 낮출 수 있다!
'프로그래밍 > Spring' 카테고리의 다른 글
Spring - ServletContext 쉽게 가져오기 (0) | 2021.01.05 |
---|---|
Spring | collection & association (0) | 2020.12.24 |
Spring | AOP (0) | 2020.12.23 |