SlideShare uma empresa Scribd logo
1 de 25
IOC & Spring Framework  이수안(inch772@naver.com) 아꿈사(http://cafe.naver.com/architect1.cafe)
Inversion of Control 객체들이 다른 객체를 invoke하는 구조가 아닌 의존되는 객체가 외부 엔터티나 컨테이너에 의해 삽입되는 구조 헐리우트 원칙 “don’t call me I will call you” Dependency injection Runtime 시점에 컨테이너에 의해 의존성들이 ‘삽입’ 된다. Bean 생성시 생성자파라메터나프로퍼티를 통해 의존성이 연결된다. 객체나 서비스 Lookup이나 객체 생성등의 하드코팅을 예방한다. 의존성을 약하게 한다. Unit Test를 효과적으로 작성하게 해준다.
Non-IoC / Dependency Injection Source: Spring Documentation
publicclassCampaignServiceImplimplementsCampaignService{ public Campaign  updateCampaign(Campaign campaign) throws CampaignException{ 	try{ 	 CampaignDAO campaign = new CampaignDAOImpl(); .. OpportunityDAOoppDAO= new OpportunityDAOImpl(); // Alternatively, initialize thru factory // OpportunityDAOoppDAO = OppFactory.getOpp(); oppDAO.save(campaign); .. 	}catch(Exception e){ } } Non-IoC Service Object
IoC / Dependency Injection Source: Spring Documentation
publicclassCampaignServiceImplimplementsCampaignService{ public Campaign updateCampaign(Campaign campaign) throws CampaignException{ 	try{ 	 oppDAO.save(campaign); 	  }catch(Exception e){ } } // Spring sets the value thru runtime injection! private setOpportunityDAO(OpportunityDAOoppDao){ this.oppDAO = oppDao; } IoC Service Object
객체의 생성, 생성 후 초기화, 서비스 실행, 소멸에 관한 모든 권한을 가지면서 생명주기를 관리한다. 예: Servlet Container, EJB Container 컨테이너? Service Init Create Destory Container 객체A 객체 B 객체C 객체 D
POJO(Plain old Java Object) Servlet과 EJB와 같이 특정 API에 종속적이지 않은 모든 자바 클래스. 일반적으로 우리들이 흔히 이야기하는 자바빈은 모두 POJO라고 이야기할 수 있다. Spring & POJO Spring의 기본 객체 관리 단위는 POJO 임 Spring은 POJO의 객체의 Life Cycle을  관리하는 IoC컨테이너 역할을 제공한다. POJO?
IoC(또는 DI) Container POJO의 생성, 초기화, 서비스 소멸에 관한 모든 권한을 가지면서 POJO의 생명주기를 관리한다. 개발자들이 직접 POJO를 생성할 수도 있지만,  모든 권한을 Container에게 맡긴다. Transaction, Security 추가적인 기능을 제공한다. AOP 기능을 이용하여 새로운 Container 기능을 추가하는 것이 가능하다 IoC Container Service Init Create Destory IoC(또는 DI) Container POJO A POJO B POJO C POJO D
IoC컨테이너의 분류 IoC : Inversion of Control DI : Dependency Injection DP : Dependency Pull ,[object Object]
 SpringDP IoC Setter Inj DI Constructor Inj ,[object Object]
PicoContainerMethod Inj
A lightweight non-intrusive framework which addresses various tiers in a J2EE application. What is Spring Framework?
Not a J2EE container. Doesn’t compete with J2EE app servers. Simply provides alternatives. POJO-based, non-invasive framework which allows a la carte usage of its components.  Promotes decoupling and reusability   Reduces coding effort and enforces design discipline by providing out-of-box implicit pattern implementations such as singleton, factory, service locator etc. Removes common code issues like leaking connections and more Support for declarative transaction management Easy integration with third party tools and technologies. Spring Benefits
IoC객체를 직접 생성하지 않고 외부에서 전달 받는 구조 IoC컨테이너는 POJO의 생명 주기를 관할한다. 대표적인 POJO 기반 IoC컨테이너는 Spring Framework Spring FrameWorkPOJO-based, non-invasive framework IoC와 Spring Framework 정리
Spring IOC 예제
publicclassCreateCreditCardAccountimplementsCreateCreditCardAccountInterface { 	privateCreditLinkingInterfacecreditLinkingInterface; 	publicvoidsetCreditLinkingInterface( CreditLinkingInterfacecreditLinkingInterface) { this.creditLinkingInterface = creditLinkingInterface; 	} 	publicCreditRatingInterfacegetCreditRatingInterface() { 		returncreditRatingInterface; 	} 	publicvoidcreateCreditCardAccount(ICustomericustomer) throws Exception{ booleancrediRating = getCreditRatingInterface().getUserCreditHistoryInformation(icustomer); icustomer.setCreditRating(crediRating); 		//Good Rating 		if(crediRating){ getCreditLinkingInterface().linkCreditBankAccount(icustomer); 		} getEmailInterface().sendEmail(icustomer); } Step1. DI 고려하여 객체 작성
<beans> <bean id="createCreditCard" class="springexample.creditcardaccount.CreateCreditCardAccount"> <property name="creditRatingInterface" ref="creditRating" /> <property name="creditLinkingInterface" ref="creditLinking"/> <property name="emailInterface" ref="email"/> </bean> <bean id="creditLinking" class="springexample.creditlinking.CreditLinking"> <property name="url"> <value>http://localhost/creditLinkService</value> </property> </bean> Step2. 의존성 정의
ClassPathXmlApplicationContextappContext = newClassPathXmlApplicationContext(new String[] { "classpath:spring/springexample-creditaccount.xml”}); CreateCreditCardAccountInterfacecreditCardAccount = (CreateCreditCardAccountInterface) appContext.getBean("createCreditCard"); creditCardAccount.createCreditCardAccount(icustomer); Step3. Factory에서 받아오기
@RunWith(MockitoJUnitRunner.class) publicclassCreateCreditCardAccountTest { CreateCreditCardAccountcreateCreditCardAccount; @Mock CreditLinkingInterfacecreditLinkingInterface; @Mock CreditRatingInterfacecreditRatingInterface; @Mock EmailInterfaceemailInterface; @Before publicvoid setup(){ createCreditCardAccount = newCreateCreditCardAccount(); createCreditCardAccount.setCreditLinkingInterface(creditLinkingInterface); createCreditCardAccount.setCreditRatingInterface(creditRatingInterface); createCreditCardAccount.setEmailInterface(emailInterface); } @Test publicvoidtestCreateCreditCardAccount() throws Exception { ICustomercusomer = mock(ICustomer.class); when(creditRatingInterface.getUserCreditHistoryInformation(cusomer)).thenReturn(true); createCreditCardAccount.createCreditCardAccount(cusomer); verify(creditLinkingInterface,times(1)).linkCreditBankAccount(cusomer); } } Step4. TestCase작성

Mais conteúdo relacionado

Mais procurados

객체지향프로그래밍 특강
객체지향프로그래밍 특강객체지향프로그래밍 특강
객체지향프로그래밍 특강uEngine Solutions
 
[오픈소스컨설팅]Spring 3.1 Core
[오픈소스컨설팅]Spring 3.1 Core [오픈소스컨설팅]Spring 3.1 Core
[오픈소스컨설팅]Spring 3.1 Core Ji-Woong Choi
 
Vert.x 세미나 이지원_배포용
Vert.x 세미나 이지원_배포용Vert.x 세미나 이지원_배포용
Vert.x 세미나 이지원_배포용지원 이
 
Angular는 사실 어렵지 않습니다.
Angular는 사실 어렵지 않습니다.Angular는 사실 어렵지 않습니다.
Angular는 사실 어렵지 않습니다.장현 한
 
Spring MVC
Spring MVCSpring MVC
Spring MVCymtech
 
우아한테크세미나-우아한멀티모듈
우아한테크세미나-우아한멀티모듈우아한테크세미나-우아한멀티모듈
우아한테크세미나-우아한멀티모듈용근 권
 
Infra as Code with Packer, Ansible and Terraform
Infra as Code with Packer, Ansible and TerraformInfra as Code with Packer, Ansible and Terraform
Infra as Code with Packer, Ansible and TerraformInho Kang
 
introduce to spring cloud
introduce to spring cloudintroduce to spring cloud
introduce to spring cloudDoo Sung Eom
 
Spring mvc
Spring mvcSpring mvc
Spring mvcksain
 
아키텍트가 바라보는 Spring framework
아키텍트가 바라보는 Spring framework아키텍트가 바라보는 Spring framework
아키텍트가 바라보는 Spring frameworkHaeil Yi
 
[오픈소스컨설팅]Spring MVC
[오픈소스컨설팅]Spring MVC [오픈소스컨설팅]Spring MVC
[오픈소스컨설팅]Spring MVC Ji-Woong Choi
 
스프링 코어 강의 3부 - 웹 애플리케이션 아키텍처
스프링 코어 강의 3부 - 웹 애플리케이션 아키텍처 스프링 코어 강의 3부 - 웹 애플리케이션 아키텍처
스프링 코어 강의 3부 - 웹 애플리케이션 아키텍처 Sungchul Park
 
04.모바일 device api_실습교재
04.모바일 device api_실습교재04.모바일 device api_실습교재
04.모바일 device api_실습교재Hankyo
 
03.모바일 실습교재(모바일 공통컴포넌트 실습)
03.모바일 실습교재(모바일 공통컴포넌트 실습)03.모바일 실습교재(모바일 공통컴포넌트 실습)
03.모바일 실습교재(모바일 공통컴포넌트 실습)Hankyo
 
Angular 2 rc5 조사
Angular 2 rc5 조사Angular 2 rc5 조사
Angular 2 rc5 조사Rjs Ryu
 
Mastering devops with oracle 강인호
Mastering devops with oracle 강인호Mastering devops with oracle 강인호
Mastering devops with oracle 강인호Inho Kang
 
kubernetes : From beginner to Advanced
kubernetes : From beginner to Advancedkubernetes : From beginner to Advanced
kubernetes : From beginner to AdvancedInho Kang
 

Mais procurados (20)

2015 oce specification
2015 oce specification2015 oce specification
2015 oce specification
 
1.스프링프레임워크 개요
1.스프링프레임워크 개요1.스프링프레임워크 개요
1.스프링프레임워크 개요
 
객체지향프로그래밍 특강
객체지향프로그래밍 특강객체지향프로그래밍 특강
객체지향프로그래밍 특강
 
[오픈소스컨설팅]Spring 3.1 Core
[오픈소스컨설팅]Spring 3.1 Core [오픈소스컨설팅]Spring 3.1 Core
[오픈소스컨설팅]Spring 3.1 Core
 
Vert.x 세미나 이지원_배포용
Vert.x 세미나 이지원_배포용Vert.x 세미나 이지원_배포용
Vert.x 세미나 이지원_배포용
 
Angular는 사실 어렵지 않습니다.
Angular는 사실 어렵지 않습니다.Angular는 사실 어렵지 않습니다.
Angular는 사실 어렵지 않습니다.
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
우아한테크세미나-우아한멀티모듈
우아한테크세미나-우아한멀티모듈우아한테크세미나-우아한멀티모듈
우아한테크세미나-우아한멀티모듈
 
Infra as Code with Packer, Ansible and Terraform
Infra as Code with Packer, Ansible and TerraformInfra as Code with Packer, Ansible and Terraform
Infra as Code with Packer, Ansible and Terraform
 
introduce to spring cloud
introduce to spring cloudintroduce to spring cloud
introduce to spring cloud
 
DevOps Demo
DevOps DemoDevOps Demo
DevOps Demo
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
아키텍트가 바라보는 Spring framework
아키텍트가 바라보는 Spring framework아키텍트가 바라보는 Spring framework
아키텍트가 바라보는 Spring framework
 
[오픈소스컨설팅]Spring MVC
[오픈소스컨설팅]Spring MVC [오픈소스컨설팅]Spring MVC
[오픈소스컨설팅]Spring MVC
 
스프링 코어 강의 3부 - 웹 애플리케이션 아키텍처
스프링 코어 강의 3부 - 웹 애플리케이션 아키텍처 스프링 코어 강의 3부 - 웹 애플리케이션 아키텍처
스프링 코어 강의 3부 - 웹 애플리케이션 아키텍처
 
04.모바일 device api_실습교재
04.모바일 device api_실습교재04.모바일 device api_실습교재
04.모바일 device api_실습교재
 
03.모바일 실습교재(모바일 공통컴포넌트 실습)
03.모바일 실습교재(모바일 공통컴포넌트 실습)03.모바일 실습교재(모바일 공통컴포넌트 실습)
03.모바일 실습교재(모바일 공통컴포넌트 실습)
 
Angular 2 rc5 조사
Angular 2 rc5 조사Angular 2 rc5 조사
Angular 2 rc5 조사
 
Mastering devops with oracle 강인호
Mastering devops with oracle 강인호Mastering devops with oracle 강인호
Mastering devops with oracle 강인호
 
kubernetes : From beginner to Advanced
kubernetes : From beginner to Advancedkubernetes : From beginner to Advanced
kubernetes : From beginner to Advanced
 

Destaque

Spring Framework 튜토리얼 - 네이버 최영목님
Spring Framework 튜토리얼 - 네이버 최영목님Spring Framework 튜토리얼 - 네이버 최영목님
Spring Framework 튜토리얼 - 네이버 최영목님NAVER D2
 
스프링 코어 강의 1부 - 봄 맞이 준비 운동
스프링 코어 강의 1부 - 봄 맞이 준비 운동스프링 코어 강의 1부 - 봄 맞이 준비 운동
스프링 코어 강의 1부 - 봄 맞이 준비 운동Sungchul Park
 
Apresentação1 Escalas Beck
Apresentação1 Escalas BeckApresentação1 Escalas Beck
Apresentação1 Escalas Beckmicaterres
 
Slide sobre o teste Escalas Beck
Slide sobre o teste Escalas Beck Slide sobre o teste Escalas Beck
Slide sobre o teste Escalas Beck Darciane Brito
 
Springcamp spring boot intro
Springcamp spring boot introSpringcamp spring boot intro
Springcamp spring boot introJae-il Lee
 
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration수홍 이
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 

Destaque (7)

Spring Framework 튜토리얼 - 네이버 최영목님
Spring Framework 튜토리얼 - 네이버 최영목님Spring Framework 튜토리얼 - 네이버 최영목님
Spring Framework 튜토리얼 - 네이버 최영목님
 
스프링 코어 강의 1부 - 봄 맞이 준비 운동
스프링 코어 강의 1부 - 봄 맞이 준비 운동스프링 코어 강의 1부 - 봄 맞이 준비 운동
스프링 코어 강의 1부 - 봄 맞이 준비 운동
 
Apresentação1 Escalas Beck
Apresentação1 Escalas BeckApresentação1 Escalas Beck
Apresentação1 Escalas Beck
 
Slide sobre o teste Escalas Beck
Slide sobre o teste Escalas Beck Slide sobre o teste Escalas Beck
Slide sobre o teste Escalas Beck
 
Springcamp spring boot intro
Springcamp spring boot introSpringcamp spring boot intro
Springcamp spring boot intro
 
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
스프링캠프 2016 발표 - Deep dive into spring boot autoconfiguration
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 

Semelhante a Spring IoC

Spring vs. spring boot
Spring vs. spring bootSpring vs. spring boot
Spring vs. spring bootChloeChoi23
 
자바 웹 개발 시작하기 (5주차 : 스프링 프래임워크)
자바 웹 개발 시작하기 (5주차 : 스프링 프래임워크)자바 웹 개발 시작하기 (5주차 : 스프링 프래임워크)
자바 웹 개발 시작하기 (5주차 : 스프링 프래임워크)DK Lee
 
HOONS닷넷 오픈소스 프로젝트 Part1.
HOONS닷넷 오픈소스 프로젝트 Part1.HOONS닷넷 오픈소스 프로젝트 Part1.
HOONS닷넷 오픈소스 프로젝트 Part1.Hojin Jun
 
[스프링 스터디 2일차] IoC 컨테이너와 DI
[스프링 스터디 2일차] IoC 컨테이너와 DI[스프링 스터디 2일차] IoC 컨테이너와 DI
[스프링 스터디 2일차] IoC 컨테이너와 DIAnselmKim
 
NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스 ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...
NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스  ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스  ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...
NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스 ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스 ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...
NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스  ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스  ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...
NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스 ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
[Spring]오브젝트와 의존관계
[Spring]오브젝트와 의존관계[Spring]오브젝트와 의존관계
[Spring]오브젝트와 의존관계slowstarter
 
(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Spring3 발표자료 - 김연수
Spring3 발표자료 - 김연수Spring3 발표자료 - 김연수
Spring3 발표자료 - 김연수Yeon Soo Kim
 
Dagger 2.0 을 활용한 의존성 주입
Dagger 2.0 을 활용한 의존성 주입Dagger 2.0 을 활용한 의존성 주입
Dagger 2.0 을 활용한 의존성 주입승용 윤
 
Continuous Integration
Continuous IntegrationContinuous Integration
Continuous IntegrationDonghyun Seo
 
반복적인 작업이 싫은 안드로이드 개발자에게
반복적인 작업이 싫은 안드로이드 개발자에게반복적인 작업이 싫은 안드로이드 개발자에게
반복적인 작업이 싫은 안드로이드 개발자에게Sungju Jin
 
[H3 2012] Bridge over troubled water : make plug-in for Appspresso
[H3 2012] Bridge over troubled water : make plug-in for Appspresso[H3 2012] Bridge over troubled water : make plug-in for Appspresso
[H3 2012] Bridge over troubled water : make plug-in for AppspressoKTH, 케이티하이텔
 
(편집-테스트카페 발표자료) 1인 QA 수행사례로 발표한 자료 (W프로젝트 사례)
(편집-테스트카페 발표자료) 1인 QA 수행사례로 발표한 자료 (W프로젝트 사례)(편집-테스트카페 발표자료) 1인 QA 수행사례로 발표한 자료 (W프로젝트 사례)
(편집-테스트카페 발표자료) 1인 QA 수행사례로 발표한 자료 (W프로젝트 사례)SangIn Choung
 
React native development
React native developmentReact native development
React native developmentSangSun Park
 
아이폰 앱 패턴
아이폰 앱 패턴아이폰 앱 패턴
아이폰 앱 패턴조 용구
 
2007년 제8회 JCO 컨퍼런스 POJO 프로그래밍 발표 자료
2007년 제8회 JCO 컨퍼런스 POJO 프로그래밍 발표 자료2007년 제8회 JCO 컨퍼런스 POJO 프로그래밍 발표 자료
2007년 제8회 JCO 컨퍼런스 POJO 프로그래밍 발표 자료beom kyun choi
 

Semelhante a Spring IoC (20)

Spring vs. spring boot
Spring vs. spring bootSpring vs. spring boot
Spring vs. spring boot
 
자바 웹 개발 시작하기 (5주차 : 스프링 프래임워크)
자바 웹 개발 시작하기 (5주차 : 스프링 프래임워크)자바 웹 개발 시작하기 (5주차 : 스프링 프래임워크)
자바 웹 개발 시작하기 (5주차 : 스프링 프래임워크)
 
HOONS닷넷 오픈소스 프로젝트 Part1.
HOONS닷넷 오픈소스 프로젝트 Part1.HOONS닷넷 오픈소스 프로젝트 Part1.
HOONS닷넷 오픈소스 프로젝트 Part1.
 
[스프링 스터디 2일차] IoC 컨테이너와 DI
[스프링 스터디 2일차] IoC 컨테이너와 DI[스프링 스터디 2일차] IoC 컨테이너와 DI
[스프링 스터디 2일차] IoC 컨테이너와 DI
 
NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스 ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...
NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스  ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스  ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...
NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스 ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...
 
NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스 ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...
NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스  ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스  ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...
NCS기반 Spring Framework & MyBatis_ 스프링프레임워크 & 마이바티스 ☆무료강의자료 제공/ 구로오라클학원, 탑크리에...
 
[Spring]오브젝트와 의존관계
[Spring]오브젝트와 의존관계[Spring]오브젝트와 의존관계
[Spring]오브젝트와 의존관계
 
(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
 
Spring3 발표자료 - 김연수
Spring3 발표자료 - 김연수Spring3 발표자료 - 김연수
Spring3 발표자료 - 김연수
 
Dagger 2.0 을 활용한 의존성 주입
Dagger 2.0 을 활용한 의존성 주입Dagger 2.0 을 활용한 의존성 주입
Dagger 2.0 을 활용한 의존성 주입
 
Continuous Integration
Continuous IntegrationContinuous Integration
Continuous Integration
 
ecdevday4
ecdevday4ecdevday4
ecdevday4
 
반복적인 작업이 싫은 안드로이드 개발자에게
반복적인 작업이 싫은 안드로이드 개발자에게반복적인 작업이 싫은 안드로이드 개발자에게
반복적인 작업이 싫은 안드로이드 개발자에게
 
Spring boot DI
Spring boot DISpring boot DI
Spring boot DI
 
[H3 2012] Bridge over troubled water : make plug-in for Appspresso
[H3 2012] Bridge over troubled water : make plug-in for Appspresso[H3 2012] Bridge over troubled water : make plug-in for Appspresso
[H3 2012] Bridge over troubled water : make plug-in for Appspresso
 
(편집-테스트카페 발표자료) 1인 QA 수행사례로 발표한 자료 (W프로젝트 사례)
(편집-테스트카페 발표자료) 1인 QA 수행사례로 발표한 자료 (W프로젝트 사례)(편집-테스트카페 발표자료) 1인 QA 수행사례로 발표한 자료 (W프로젝트 사례)
(편집-테스트카페 발표자료) 1인 QA 수행사례로 발표한 자료 (W프로젝트 사례)
 
React native development
React native developmentReact native development
React native development
 
My di container
My di containerMy di container
My di container
 
아이폰 앱 패턴
아이폰 앱 패턴아이폰 앱 패턴
아이폰 앱 패턴
 
2007년 제8회 JCO 컨퍼런스 POJO 프로그래밍 발표 자료
2007년 제8회 JCO 컨퍼런스 POJO 프로그래밍 발표 자료2007년 제8회 JCO 컨퍼런스 POJO 프로그래밍 발표 자료
2007년 제8회 JCO 컨퍼런스 POJO 프로그래밍 발표 자료
 

Mais de Suan Lee

HTML5 & CSS 살펴보기
HTML5 & CSS  살펴보기HTML5 & CSS  살펴보기
HTML5 & CSS 살펴보기Suan Lee
 
Pmp 자격증 도전기
Pmp 자격증 도전기Pmp 자격증 도전기
Pmp 자격증 도전기Suan Lee
 
ApprenticeshipPatterns/Chapter5
ApprenticeshipPatterns/Chapter5ApprenticeshipPatterns/Chapter5
ApprenticeshipPatterns/Chapter5Suan Lee
 
데이터베이스패턴
데이터베이스패턴데이터베이스패턴
데이터베이스패턴Suan Lee
 
maven 소개
maven 소개maven 소개
maven 소개Suan Lee
 

Mais de Suan Lee (6)

HTML5 & CSS 살펴보기
HTML5 & CSS  살펴보기HTML5 & CSS  살펴보기
HTML5 & CSS 살펴보기
 
Pmp 자격증 도전기
Pmp 자격증 도전기Pmp 자격증 도전기
Pmp 자격증 도전기
 
ApprenticeshipPatterns/Chapter5
ApprenticeshipPatterns/Chapter5ApprenticeshipPatterns/Chapter5
ApprenticeshipPatterns/Chapter5
 
데이터베이스패턴
데이터베이스패턴데이터베이스패턴
데이터베이스패턴
 
maven 소개
maven 소개maven 소개
maven 소개
 
Maven
MavenMaven
Maven
 

Spring IoC

  • 1. IOC & Spring Framework 이수안(inch772@naver.com) 아꿈사(http://cafe.naver.com/architect1.cafe)
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7. Inversion of Control 객체들이 다른 객체를 invoke하는 구조가 아닌 의존되는 객체가 외부 엔터티나 컨테이너에 의해 삽입되는 구조 헐리우트 원칙 “don’t call me I will call you” Dependency injection Runtime 시점에 컨테이너에 의해 의존성들이 ‘삽입’ 된다. Bean 생성시 생성자파라메터나프로퍼티를 통해 의존성이 연결된다. 객체나 서비스 Lookup이나 객체 생성등의 하드코팅을 예방한다. 의존성을 약하게 한다. Unit Test를 효과적으로 작성하게 해준다.
  • 8. Non-IoC / Dependency Injection Source: Spring Documentation
  • 9. publicclassCampaignServiceImplimplementsCampaignService{ public Campaign updateCampaign(Campaign campaign) throws CampaignException{ try{ CampaignDAO campaign = new CampaignDAOImpl(); .. OpportunityDAOoppDAO= new OpportunityDAOImpl(); // Alternatively, initialize thru factory // OpportunityDAOoppDAO = OppFactory.getOpp(); oppDAO.save(campaign); .. }catch(Exception e){ } } Non-IoC Service Object
  • 10. IoC / Dependency Injection Source: Spring Documentation
  • 11. publicclassCampaignServiceImplimplementsCampaignService{ public Campaign updateCampaign(Campaign campaign) throws CampaignException{ try{ oppDAO.save(campaign); }catch(Exception e){ } } // Spring sets the value thru runtime injection! private setOpportunityDAO(OpportunityDAOoppDao){ this.oppDAO = oppDao; } IoC Service Object
  • 12. 객체의 생성, 생성 후 초기화, 서비스 실행, 소멸에 관한 모든 권한을 가지면서 생명주기를 관리한다. 예: Servlet Container, EJB Container 컨테이너? Service Init Create Destory Container 객체A 객체 B 객체C 객체 D
  • 13. POJO(Plain old Java Object) Servlet과 EJB와 같이 특정 API에 종속적이지 않은 모든 자바 클래스. 일반적으로 우리들이 흔히 이야기하는 자바빈은 모두 POJO라고 이야기할 수 있다. Spring & POJO Spring의 기본 객체 관리 단위는 POJO 임 Spring은 POJO의 객체의 Life Cycle을 관리하는 IoC컨테이너 역할을 제공한다. POJO?
  • 14. IoC(또는 DI) Container POJO의 생성, 초기화, 서비스 소멸에 관한 모든 권한을 가지면서 POJO의 생명주기를 관리한다. 개발자들이 직접 POJO를 생성할 수도 있지만, 모든 권한을 Container에게 맡긴다. Transaction, Security 추가적인 기능을 제공한다. AOP 기능을 이용하여 새로운 Container 기능을 추가하는 것이 가능하다 IoC Container Service Init Create Destory IoC(또는 DI) Container POJO A POJO B POJO C POJO D
  • 15.
  • 16.
  • 18. A lightweight non-intrusive framework which addresses various tiers in a J2EE application. What is Spring Framework?
  • 19. Not a J2EE container. Doesn’t compete with J2EE app servers. Simply provides alternatives. POJO-based, non-invasive framework which allows a la carte usage of its components. Promotes decoupling and reusability Reduces coding effort and enforces design discipline by providing out-of-box implicit pattern implementations such as singleton, factory, service locator etc. Removes common code issues like leaking connections and more Support for declarative transaction management Easy integration with third party tools and technologies. Spring Benefits
  • 20. IoC객체를 직접 생성하지 않고 외부에서 전달 받는 구조 IoC컨테이너는 POJO의 생명 주기를 관할한다. 대표적인 POJO 기반 IoC컨테이너는 Spring Framework Spring FrameWorkPOJO-based, non-invasive framework IoC와 Spring Framework 정리
  • 22. publicclassCreateCreditCardAccountimplementsCreateCreditCardAccountInterface { privateCreditLinkingInterfacecreditLinkingInterface; publicvoidsetCreditLinkingInterface( CreditLinkingInterfacecreditLinkingInterface) { this.creditLinkingInterface = creditLinkingInterface; } publicCreditRatingInterfacegetCreditRatingInterface() { returncreditRatingInterface; } publicvoidcreateCreditCardAccount(ICustomericustomer) throws Exception{ booleancrediRating = getCreditRatingInterface().getUserCreditHistoryInformation(icustomer); icustomer.setCreditRating(crediRating); //Good Rating if(crediRating){ getCreditLinkingInterface().linkCreditBankAccount(icustomer); } getEmailInterface().sendEmail(icustomer); } Step1. DI 고려하여 객체 작성
  • 23. <beans> <bean id="createCreditCard" class="springexample.creditcardaccount.CreateCreditCardAccount"> <property name="creditRatingInterface" ref="creditRating" /> <property name="creditLinkingInterface" ref="creditLinking"/> <property name="emailInterface" ref="email"/> </bean> <bean id="creditLinking" class="springexample.creditlinking.CreditLinking"> <property name="url"> <value>http://localhost/creditLinkService</value> </property> </bean> Step2. 의존성 정의
  • 24. ClassPathXmlApplicationContextappContext = newClassPathXmlApplicationContext(new String[] { "classpath:spring/springexample-creditaccount.xml”}); CreateCreditCardAccountInterfacecreditCardAccount = (CreateCreditCardAccountInterface) appContext.getBean("createCreditCard"); creditCardAccount.createCreditCardAccount(icustomer); Step3. Factory에서 받아오기
  • 25. @RunWith(MockitoJUnitRunner.class) publicclassCreateCreditCardAccountTest { CreateCreditCardAccountcreateCreditCardAccount; @Mock CreditLinkingInterfacecreditLinkingInterface; @Mock CreditRatingInterfacecreditRatingInterface; @Mock EmailInterfaceemailInterface; @Before publicvoid setup(){ createCreditCardAccount = newCreateCreditCardAccount(); createCreditCardAccount.setCreditLinkingInterface(creditLinkingInterface); createCreditCardAccount.setCreditRatingInterface(creditRatingInterface); createCreditCardAccount.setEmailInterface(emailInterface); } @Test publicvoidtestCreateCreditCardAccount() throws Exception { ICustomercusomer = mock(ICustomer.class); when(creditRatingInterface.getUserCreditHistoryInformation(cusomer)).thenReturn(true); createCreditCardAccount.createCreditCardAccount(cusomer); verify(creditLinkingInterface,times(1)).linkCreditBankAccount(cusomer); } } Step4. TestCase작성
  • 26. 구현은 Setter를 통해 의존성을 전달받음 이때 의존성은 모두 Concrete Class가 아닌 Interface 기반임 외부 XML파일로 의존성 정의 Spring Bean Factory는 설정을 읽어 객체를 생성함 테스트 케이스 작성시 관심 없는 부분은 Mock처리하여 쉽게 작성할 수 있음 DI 예제 정리