티스토리 뷰

 DI 는 스프링 컨테이너가 지원하는 핵심 개념 중 하나이다. DI 는 객체 사이의 의존 관계를 객체 자신이 아닌 외부의 조립기 스프링 컨테이너 가 수행한다는 개념이다.

 

기존에는 다음과 같이 의존하는 객체를 직접 코드에 명시했지만,

스프링에서는 설정 파일이나 어노테이션을 이용하여 객체 간의 의존 관계를 설정할 수 있다.


◎ Spring beans 를 활용한 의존성 주입

 

의존성 주입에 대한 간단한 구조 설명이므로, Web Project가 아닌 일반 java application으로 진행했다.

 

1. TestDao 인터페이스 생성

 

◎TestDao

package test;

public interface TestDao {
	void printMessage();
}

 

2. TestDao 인터페이스를 구현 받는 TestDaoImp 생성 & 메서드 정의

 

◎TestDaoImp

package test;

public class TestDaoImp implements TestDao{

	public TestDaoImp() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void printMessage() {
		
		System.out.println("TestDaoImp의 printMessage()! ");
		
	}

}

 

3. test.xml 생성 후 beans 구성, 등록

 

◎test.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 = "testDaoImp" class = "test.TestDaoImp">
	
	</bean>
	
</beans>
	

 

4. Main에서 호출

 

◎testMain

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class testMain {

	public testMain() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
          //TestDaoImp의 printMessage() 를 호출

          /**
          * Spring이 아닌 기존 자바형식
          * TestDaoImp tdi = new TestDaoImp();
          * tdi.printMessage();
          **/

          ApplicationContext context = new FileSystemXmlApplicationContext("src/test/test.xml");
          TestDao testDao = (TestDao)context.getBean("testDaoImp");

          System.out.println("Start");

          testDao.printMessage();

          System.out.println("end");

	}

}

이렇게 프로젝트를 구성하게되면, 만약에 DAO를 다른 DAO로 변경할 일이 생겼을 때,  해당 DAO를 호출하는 모든 코드가 아닌 xml 문서의 bean 태그만 수정하면 되기 때문에 유지보수가 매우 편리하게 된다.

 

Comments