DI(Dependency Injection)

박찬호·2022년 4월 20일
0

Spring

목록 보기
4/6

개념

Dependency Injection:
객체 간의 의존관계를 자신이 아닌 외부의 조립기가 수행.
제어의 역행(IoC)라는 의미로 사용
DI를 통해 시스템에 있는 각 객체를 조정하는 외부 개체가 객체들에게 생성시에 의존관계를 주어짐

DI의 주요 강점은 느슨한 결합이다.

객체는 인터페이스에 의한 의존관계만을 알고 있으며, 이 의존 관계는 구현 클래스에 대한 차이를 모르는 채 서로 다른 구현으로 대체 가능

스프링의 DI 지원

Spring Container가 DI 조립기를 제공한다.
스프링 설정 파일을 통해 객체간의 의존관계를 설정할 수 있다.

DI - XML

Spring Container는 설정파일에 설정된 내용을 읽어 Application에서 필요한 기능들을 제공한다.

Root tag는 < beans >이다. 파일명은 상관 없음.

bean객체 주입 코드

<?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 = "ds" class ="org.springframework.jdbc.datasource.SimpleDriverDataSource">
		<property name="url" value = "jdbc:mysql://127.0.0.1:3306/ssafyweb?serverTimezone=UTC&amp;useUniCode=yes&amp;characterEncoding=UTF-8"></property>
		<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
		<property name="username" value = "root"></property>
		<property name="password" value = "ghkdth429"></property>
	</bean>
	<bean id = "gbDao" class ="com.ssafy.model.dao.GuestBookDaoImpl">
		<property name="dataSource" ref="ds"></property>
	</bean>
	<bean id = "gbService" class ="com.ssafy.model.service.GuestBookServiceImpl">
		<property name="guestBookDao" ref="gbDao"></property>
	</bean>

</beans>
  • < bean > - 스프링 컨테이너가 관리할 Bean객체를 설정
  • id: 주입 받을 곳에서 호출할 이름
  • class: 주입 할 객체 클래스
  • init-method: init method 설정

bean 객체 얻기

ApplicationContext context = new ClassPathXmlApplicationContext("com/ssafy/configuration/applicationContext.xml");
		
GuestBookService guestBookService = context.getBean("gbService", GuestBookService.class);
profile
Develop for Fun

0개의 댓글