note

Spring Di(Dipendency Injection) 본문

JSP/Spring

Spring Di(Dipendency Injection)

투한 2012. 2. 28. 12:13



Spring의 핵심인 Di


applicationContext.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-3.0.xsd">

	<bean name="writeArticleService" class="madvirus.spring.chap01.WriteArticleServiceImpl">
		<constructor-arg>
			<ref bean="articleDao"/>
		</constructor-arg>
	</bean>	
	
	<bean name="articleDao" class="madvirus.spring.chap01.MySQLArticleDao" />
</beans>


Article
package madvirus.spring.chap01;

public class Article {

}


ArticleDao
package madvirus.spring.chap01;

public interface ArticleDao {
	void insert(Article article);
}

Main
package madvirus.spring.chap01;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class Main {
	public static void main(String[] args) {
		Resource resource = new ClassPathResource("applicationContext.xml");

		BeanFactory beanFactory = new XmlBeanFactory(resource);
		WriteArticleService articleSevice = (WriteArticleService) beanFactory
				.getBean("writeArticleService");
		
		articleSevice.write(new Article());
	}
}

MySQLArticleDao
package madvirus.spring.chap01;

public class MySQLArticleDao implements ArticleDao{

	@Override
	public void insert(Article article) {
		System.out.println("MySQLArticleDao.insert()실행");
	}

}


WriteArticleService
package madvirus.spring.chap01;

public interface WriteArticleService {
	void write(Article article);
}


WriteArticleServiceImpl
package madvirus.spring.chap01;

public class WriteArticleServiceImpl implements WriteArticleService{

	private ArticleDao articleDao;


	public WriteArticleServiceImpl(ArticleDao articleDao){
		this.articleDao = articleDao;
	}
	
	@Override
	public void write(Article article) {
		System.out.println("WriteArticleServiceImpl.write() 메서드 실행");
		articleDao.insert(article);
	}

}








Main.java실행 화면

WriteArticleServiceImpl.write() 메서드 실행

MySQLArticleDao.insert()실행







객체를 호출하게 되면
자동적으로 생성자, 또는 메서드를 통해 받는것



객체 상호간의 의존관계를 객체 외부에서 제어한다


두개의 의존성 있는 객체를 자바 코드로 형성해 주는것이 아니라 밖에서(SpringContainer가 담당해준다) 






Main.java
(getBean은 찾는 메서드)
applicationContext.xml에서  writeArticleService를 찾는다