SlideShare a Scribd company logo
Spring Framework
Spring IoC & DI
Spring IoC 실습
(어노테이션기반, 인터페이스, 세터주입)
Spring Framework_Spring Ioc & DI
Spring IoC & DI
package edu.biz.ioc4;
import org.springframework.stereotype.Component;
@Component("money") // DTO같은 컴포넌트 클래스임을 의미, @Named와 동일
public class Money {
private int amount;
public Money() {
}
public Money(int amt) {
this.amount = amt;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
3. Spring IoC 실습 (어노테이션 기반, 인터페이스, 세터주입)
2-2에서 작성한 예제를 어노테이션 기반으로 변경해 보자.
[Money.java]
Spring Framework_Spring Ioc & DI
package edu.biz.ioc4;
import org.springframework.stereotype.Component;
@Component("car")
public class Car {
private String name;
public Car() {
}
public Car(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
[Car.java]
Spring Framework_Spring Ioc & DI
package edu.biz.ioc4;
public interface CarMaker {
//돈을 받고 차를 판다
public Car sell(Money money) ;
}
[CarMaker.java]
[HyundaiMaker.java]
package edu.biz.ioc4;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("hyundai") //@Named와 동일, 서비스계층의 클래스임을 의미
public class HyundaiMaker implements CarMaker{
@Autowired //@Inject와 동일
private Car car;
public Car sell(Money money) {
System.out.println("I sold a Sonata.");
car.setName("Sonata");
return car;
}
}
Spring Framework_Spring Ioc & DI
package edu.biz.ioc4;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service(“daewoo")
public class DaewooMaker implements CarMaker{
@Autowired
private Car car;
public Car sell(Money money) {
System.out.println("I sold a Tosca.");
car.setName(“Tosca");
return car;
}
}
[DaewooMaker.java]
Spring Framework_Spring Ioc & DI
package edu.biz.ioc4;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service("orderManager")
public class OrderManager {
private String name;
@Autowired // TYPE이 CarMaker 인것 찾아 자동 주입, 여러 개인 경우 Qualifier로 지정
@Qualifier("daewoo")
private CarMaker maker;
@Autowired // TYPE이 Money 인 것을 찾아 자동 주입
private Money money;
public OrderManager() {
}
public void order() {
money.setAmount(1000);
Car car = this.maker.sell(money);
}
}
[OrderManager.java]
Spring Framework_Spring Ioc & DI
<?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-4.2.xsd">
<beans>
<context:annotation-config/> ←생략가능!!→
<context:component-scan base-package="edu.biz.ioc4"/>
</beans>
[ioc4.xml]
Spring Framework_Spring Ioc & DI
package edu.biz.ioc4;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class OrderManagerApp {
public static void main(String[] args) {
ApplicationContext factory = new
ClassPathXmlApplicationContext("classpath:ioc4.xml");
OrderManager manager = (OrderManager)
factory.getBean("orderManager");
manager.order();
}
}
[OrderManagerApp.java]
 실행 후 결과를 확인하자.
Spring Framework_Spring Ioc & DI
package edu.biz.ioc4;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
@Service
public class OrderManagerApp {
//생성자가 아닌 직접 autowiring은 불가, static 변수는 autowiring 안된다.
static OrderManager orderManager;
@Autowired
public OrderManagerApp(OrderManager orderManager) {
OrderManagerApp.orderManager = orderManager;
}
public static void main(String[] args) {
ApplicationContext factory =
new ClassPathXmlApplicationContext("classpath:ioc4.xml");
//OrderManager manager = (OrderManager)
factory.getBean("orderManager");
orderManager.order();
}
}
[수정된 OrderManagerApp.java]

More Related Content

PDF
(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
PDF
#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...
PDF
Dependency injection with koin
PDF
Angular2 - In Action
PDF
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...
Dependency injection with koin
Angular2 - In Action
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...

What's hot (20)

ODT
Types of Dependency Injection in Spring
PDF
Create Your Own Framework by Fabien Potencier
ODT
Spring IOC advantages and developing spring application sample
PPTX
Angular2 + rxjs
PPTX
ODP
Jquery- One slide completing all JQuery
PDF
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
ODP
Dependency Injection, Zend Framework and Symfony Container
PDF
Data Flow Patterns in Angular 2 - Sebastian Müller
PPT
Spring AOP
PDF
#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
PPTX
PPT
ExtJs Basic Part-1
PDF
Commit University - Exploring Angular 2
PPTX
Zend Studio Tips and Tricks
PDF
Dart for Java Developers
PPTX
Angular modules in depth
PDF
Exploring Angular 2 - Episode 2
RTF
AutoComplete
PDF
Test Driven Development with JavaFX
Types of Dependency Injection in Spring
Create Your Own Framework by Fabien Potencier
Spring IOC advantages and developing spring application sample
Angular2 + rxjs
Jquery- One slide completing all JQuery
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
Dependency Injection, Zend Framework and Symfony Container
Data Flow Patterns in Angular 2 - Sebastian Müller
Spring AOP
#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
ExtJs Basic Part-1
Commit University - Exploring Angular 2
Zend Studio Tips and Tricks
Dart for Java Developers
Angular modules in depth
Exploring Angular 2 - Episode 2
AutoComplete
Test Driven Development with JavaFX
Ad

Similar to 4.Spring IoC&DI(Spring Ioc실습_어노테이션 기반) (8)

PDF
Week5 컴포넌트 스캔
PPTX
Spring data jpa simple example_스프링학원/자바학원추천/구로IT학원/자바학원
PDF
Map struct
PDF
Map struct
PDF
Week2 아주 작은 빈 이야기
PDF
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
PDF
Spring java config
PPTX
2. 엔티티 매핑(entity mapping) 2 2 엔티티매핑 2-2-4. 식별자 자동 생성(@generated-value)4
Week5 컴포넌트 스캔
Spring data jpa simple example_스프링학원/자바학원추천/구로IT학원/자바학원
Map struct
Map struct
Week2 아주 작은 빈 이야기
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
Spring java config
2. 엔티티 매핑(entity mapping) 2 2 엔티티매핑 2-2-4. 식별자 자동 생성(@generated-value)4
Ad

More from 탑크리에듀(구로디지털단지역3번출구 2분거리) (20)

PDF
자마린.안드로이드 기본 내장레이아웃(Built-In List Item Layouts)
PDF
(스프링프레임워크 강좌)스프링부트개요 및 HelloWorld 따라하기
PDF
자마린 iOS 멀티화면 컨트롤러_네비게이션 컨트롤러, 루트 뷰 컨트롤러
PPTX
[IT교육/IT학원]Develope를 위한 IT실무교육
PPTX
[아이오닉학원]아이오닉 하이브리드 앱 개발 과정(아이오닉2로 동적 모바일 앱 만들기)
PPTX
[뷰제이에스학원]뷰제이에스(Vue.js) 프로그래밍 입문(프로그레시브 자바스크립트 프레임워크)
PPTX
[씨샵학원/씨샵교육]C#, 윈폼, 네트워크, ado.net 실무프로젝트 과정
PPTX
[정보처리기사자격증학원]정보처리기사 취득 양성과정(국비무료 자격증과정)
PPTX
[wpf학원,wpf교육]닷넷, c#기반 wpf 프로그래밍 인터페이스구현 재직자 향상과정
PDF
(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...
PDF
[자마린교육/자마린실습]자바,스프링프레임워크(스프링부트) RESTful 웹서비스 구현 실습,자마린에서 스프링 웹서비스를 호출하고 응답 JS...
PPTX
[구로자마린학원/자마린강좌/자마린교육]3. xamarin.ios 3.3.5 추가적인 사항
PPTX
3. xamarin.i os 3.3 xamarin.ios helloworld 자세히 살펴보기 3.4.4 view controllers an...
PPTX
5. 서브 쿼리(sub query) 5.1 서브 쿼리(sub query) 개요 5.2 단일행 서브쿼리(single row sub query)
PPTX
3. xamarin.i os 3.1 xamarin.ios 설치, 개발환경 3.2 xamarin.ios helloworld(단일 뷰) 실습[...
PDF
(닷넷,자마린,아이폰실습)Xamarin.iOS HelloWorld 실습_멀티화면,화면전환_Xamarin교육/Xamarin강좌
PPTX
C#기초에서 윈도우, 스마트폰 앱개발 과정(c#.net, ado.net, win form, wpf, 자마린)_자마린학원_씨샵교육_WPF학원...
PPTX
자바, 웹 기초와 스프링 프레임워크 & 마이바티스 재직자 향상과정(자바학원/자바교육/자바기업출강]
PPTX
3. xamarin.i os 3.1 xamarin.ios 설치, 개발환경 3.2 xamarin.ios helloworld_자마린학원_자마린...
PPTX
3. 안드로이드 애플리케이션 구성요소 3.2인텐트 part01(안드로이드학원/안드로이드교육/안드로이드강좌/안드로이드기업출강]
자마린.안드로이드 기본 내장레이아웃(Built-In List Item Layouts)
(스프링프레임워크 강좌)스프링부트개요 및 HelloWorld 따라하기
자마린 iOS 멀티화면 컨트롤러_네비게이션 컨트롤러, 루트 뷰 컨트롤러
[IT교육/IT학원]Develope를 위한 IT실무교육
[아이오닉학원]아이오닉 하이브리드 앱 개발 과정(아이오닉2로 동적 모바일 앱 만들기)
[뷰제이에스학원]뷰제이에스(Vue.js) 프로그래밍 입문(프로그레시브 자바스크립트 프레임워크)
[씨샵학원/씨샵교육]C#, 윈폼, 네트워크, ado.net 실무프로젝트 과정
[정보처리기사자격증학원]정보처리기사 취득 양성과정(국비무료 자격증과정)
[wpf학원,wpf교육]닷넷, c#기반 wpf 프로그래밍 인터페이스구현 재직자 향상과정
(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...
[자마린교육/자마린실습]자바,스프링프레임워크(스프링부트) RESTful 웹서비스 구현 실습,자마린에서 스프링 웹서비스를 호출하고 응답 JS...
[구로자마린학원/자마린강좌/자마린교육]3. xamarin.ios 3.3.5 추가적인 사항
3. xamarin.i os 3.3 xamarin.ios helloworld 자세히 살펴보기 3.4.4 view controllers an...
5. 서브 쿼리(sub query) 5.1 서브 쿼리(sub query) 개요 5.2 단일행 서브쿼리(single row sub query)
3. xamarin.i os 3.1 xamarin.ios 설치, 개발환경 3.2 xamarin.ios helloworld(단일 뷰) 실습[...
(닷넷,자마린,아이폰실습)Xamarin.iOS HelloWorld 실습_멀티화면,화면전환_Xamarin교육/Xamarin강좌
C#기초에서 윈도우, 스마트폰 앱개발 과정(c#.net, ado.net, win form, wpf, 자마린)_자마린학원_씨샵교육_WPF학원...
자바, 웹 기초와 스프링 프레임워크 & 마이바티스 재직자 향상과정(자바학원/자바교육/자바기업출강]
3. xamarin.i os 3.1 xamarin.ios 설치, 개발환경 3.2 xamarin.ios helloworld_자마린학원_자마린...
3. 안드로이드 애플리케이션 구성요소 3.2인텐트 part01(안드로이드학원/안드로이드교육/안드로이드강좌/안드로이드기업출강]

Recently uploaded (20)

PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Computing-Curriculum for Schools in Ghana
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Classroom Observation Tools for Teachers
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Basic Mud Logging Guide for educational purpose
PPTX
GDM (1) (1).pptx small presentation for students
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
01-Introduction-to-Information-Management.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Computing-Curriculum for Schools in Ghana
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Classroom Observation Tools for Teachers
Module 4: Burden of Disease Tutorial Slides S2 2025
102 student loan defaulters named and shamed – Is someone you know on the list?
Basic Mud Logging Guide for educational purpose
GDM (1) (1).pptx small presentation for students
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
VCE English Exam - Section C Student Revision Booklet
Microbial diseases, their pathogenesis and prophylaxis
human mycosis Human fungal infections are called human mycosis..pptx
Final Presentation General Medicine 03-08-2024.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student

4.Spring IoC&DI(Spring Ioc실습_어노테이션 기반)

  • 1. Spring Framework Spring IoC & DI Spring IoC 실습 (어노테이션기반, 인터페이스, 세터주입)
  • 2. Spring Framework_Spring Ioc & DI Spring IoC & DI package edu.biz.ioc4; import org.springframework.stereotype.Component; @Component("money") // DTO같은 컴포넌트 클래스임을 의미, @Named와 동일 public class Money { private int amount; public Money() { } public Money(int amt) { this.amount = amt; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } 3. Spring IoC 실습 (어노테이션 기반, 인터페이스, 세터주입) 2-2에서 작성한 예제를 어노테이션 기반으로 변경해 보자. [Money.java]
  • 3. Spring Framework_Spring Ioc & DI package edu.biz.ioc4; import org.springframework.stereotype.Component; @Component("car") public class Car { private String name; public Car() { } public Car(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } [Car.java]
  • 4. Spring Framework_Spring Ioc & DI package edu.biz.ioc4; public interface CarMaker { //돈을 받고 차를 판다 public Car sell(Money money) ; } [CarMaker.java] [HyundaiMaker.java] package edu.biz.ioc4; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("hyundai") //@Named와 동일, 서비스계층의 클래스임을 의미 public class HyundaiMaker implements CarMaker{ @Autowired //@Inject와 동일 private Car car; public Car sell(Money money) { System.out.println("I sold a Sonata."); car.setName("Sonata"); return car; } }
  • 5. Spring Framework_Spring Ioc & DI package edu.biz.ioc4; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service(“daewoo") public class DaewooMaker implements CarMaker{ @Autowired private Car car; public Car sell(Money money) { System.out.println("I sold a Tosca."); car.setName(“Tosca"); return car; } } [DaewooMaker.java]
  • 6. Spring Framework_Spring Ioc & DI package edu.biz.ioc4; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service("orderManager") public class OrderManager { private String name; @Autowired // TYPE이 CarMaker 인것 찾아 자동 주입, 여러 개인 경우 Qualifier로 지정 @Qualifier("daewoo") private CarMaker maker; @Autowired // TYPE이 Money 인 것을 찾아 자동 주입 private Money money; public OrderManager() { } public void order() { money.setAmount(1000); Car car = this.maker.sell(money); } } [OrderManager.java]
  • 7. Spring Framework_Spring Ioc & DI <?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-4.2.xsd"> <beans> <context:annotation-config/> ←생략가능!!→ <context:component-scan base-package="edu.biz.ioc4"/> </beans> [ioc4.xml]
  • 8. Spring Framework_Spring Ioc & DI package edu.biz.ioc4; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class OrderManagerApp { public static void main(String[] args) { ApplicationContext factory = new ClassPathXmlApplicationContext("classpath:ioc4.xml"); OrderManager manager = (OrderManager) factory.getBean("orderManager"); manager.order(); } } [OrderManagerApp.java]  실행 후 결과를 확인하자.
  • 9. Spring Framework_Spring Ioc & DI package edu.biz.ioc4; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Service; @Service public class OrderManagerApp { //생성자가 아닌 직접 autowiring은 불가, static 변수는 autowiring 안된다. static OrderManager orderManager; @Autowired public OrderManagerApp(OrderManager orderManager) { OrderManagerApp.orderManager = orderManager; } public static void main(String[] args) { ApplicationContext factory = new ClassPathXmlApplicationContext("classpath:ioc4.xml"); //OrderManager manager = (OrderManager) factory.getBean("orderManager"); orderManager.order(); } } [수정된 OrderManagerApp.java]