●di1 패키지 생성
예제 에서 사용할 HotAmericano 클래스
package di1;
public class HotAmericano {
public String getName(){
return"따듯한 아메리카노~";
}
}
예제 에서 사용할 Coffee 클래스
package di1;
public class Coffee {
private HotAmericano ame;
public Coffee(){
ame = new HotAmericano();
}
public void coffeeType(){
System.out.println(ame.getName());
}
}
예제를 돌려보자.
package di1;
public class Test {
public static void main(String[] args){
Coffee coffee = new Coffee();
coffee.coffeeType();
}
}
실행결과 : 따듯한 아메리카노~
이걸 차가운 아메리카노로 바꾸고 싶다면 ??
차가운 아메리카노를 만들자
package di1;
public class IceAmericano {
public String getName(){
return"차가운 아메리카노";
}
}
커피를 hot에서 ice로 바꾸고 싶으면 이 코드를 수정해야한다↓
package di1;
public class Coffee {
private HotAmericano ame;
public Coffee(){
ame = new HotAmericano();
}
public void coffeeType(){
System.out.println(ame.getName());
}
}
의존성을 걷어 내려면 타입과 객체생성을 걷어 내야한다.
타입걷어내기 → 인터페이스 끼고 느슨한 결합
객체생성 걷어내기 → 직접 안만들고 매개변수로 받기
●타입과 객체생성을 걷어내는 버전 di2 패키지를 만들자
di1 패키지 클래스를 모두 복사 해서 붙혀놓는다.
타입을 겉어내는데 사용할 인터페이스 Americano
package di2;
public interface Americano {
public String getName();
}
Hot, Ice 각각 Americano를 implements 해주자!
package di2;
public class HotAmericano implements Americano{
public String getName(){
return"따듯한 아메리카노~";
}
}
package di2;
public class IceAmericano implements Americano{
public String getName(){
return"차가운 아메리카노";
}
}
그리고 Coffee 클래스에도 아메리카노 인터페이스로 바꿔주자!
package di2;
public class Coffee {
private Americano americano;
public Coffee(){
americano = new HotAmericano();
}
public void coffeeType(){
System.out.println(americano.getName());
}
}
이렇게 되면 아메리카노의 ice와hot을 바꿀때 객체 생성만 건드리면 된다!
객체 생성을 걷어내는 방법은 의존성주입!
의존성 주입중에 생성자 주입 방법을 보자!
package di2;
public class Coffee {
private Americano americano;
public Coffee(Americano ame){
americano = ame;
}
public void coffeeType(){
System.out.println(americano.getName());
}
}
이제 커피를 만드려면 ice or hot 아메리카노를 만들어서 넣어줘야된다.
package di2;
public class Test {
public static void main(String[] args){
// HotAmericano hot = new HotAmericano();
IceAmericano ice = new IceAmericano();
Coffee coffee = new Coffee(ice);
coffee.coffeeType();
}
}
이제 아메리카노의 온도를 바꾸고 싶을때 Coffee클래스는 건드릴 코드가 없어졌다.
Coffee와 Americano 간의 의존성이 사라졌다.
온도를 바꾸려면 Test클래스가 변해야된다. 커피의 아메리카노에 대한 의존성이 Test로 전가된것이다.
이게 바로 제어의 역행!
이런식으로 역행 역행........역행 해서 한곳에 의존성을 몰아줄수 있다.
그 한곳을 스프링 컨테이너에 하자. 스프링컨테이너는 IoC컨테이너 라고도 불린다.
●di3 패기지를 만들어서 설정자 주입버전으로 만들어보자.
di2에 있는 클래스를 모두 복사해서 di3에 붙혀놓기.
package di3;
public class Coffee {
private Americano americano;
// public Coffee(Americano ame){
// americano = ame;
// }
public void setCoffe(Americano americano){
this.americano = americano;
}
public void coffeeType(){
System.out.println(americano.getName());
}
}
setter를 통해서 받는 설정자 주입.
package di3;
public class Test {
public static void main(String[] args){
HotAmericano hot = new HotAmericano();
// IceAmericano ice = new IceAmericano();
Coffee coffee = new Coffee();
coffee.setCoffe(hot);
coffee.coffeeType();
}
}
● di1 패키지 내용 중 Test클래스에서 Coffee객체를 만드는 과정을 스프링 컨테이너에 빈(bean)객체로 등록해두고 찾아오는 di4를 만들어보자. di1 패키지 안의 클래스를 모두 복사해서 붙혀놓자.
xml스프링 설정파일 작성
자바코드에서 xml설정파일을 매개로 해서 ApplicationContext객체 생성
컨테이너 객체로부터 bean객체 얻어다 쓰기
스프링 설정파일 만들기!
패키지 우클릭 → New → Other → Spring 폴더 찾아서 밑에 Spring Bean Configuration File 누르고 next
→ 이름은 관례적으로 applicationContext.xml 많이 사용함. 하고 finish
<?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="coffee" class="di4.Coffee"></bean>
</beans>
id = "변수명" class="클래스명(풀패키지)"
스프링 설정파일을 매개로 컨테이너 빌드 하고, 컨테이너로 부터 객체 획득하기
package di4;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class Test {
public static void main(String[] args){
// Coffee coffee = new Coffee();
// coffee.coffeeType();
ApplicationContext context = new GenericXmlApplicationContext("di4/applicationContext.xml");
// Coffee coffee = (Coffee)context.getBean("coffee"); //직접 형변환 하는법
Coffee coffee = context.getBean("coffee", Coffee.class); //클래스 정보를 같이 넘겨주는 방법
coffee.coffeeType();
}
}
스프링 컨테이너의 기본 객체관리 정책은 컨테이너 생성시 자신이 포함할 빈 객체를 모두 생성.
객체를 제거하는거는 컨테이너가 삭제될때 다 제거하거 죽음.
<bean id="coffee" class="di4.Coffee" lazy-init="true"></bean>
lazy-init속성을 true로 주시면 이 객체는 첫번째 getBean이 일어날때까지 객체를 만들지 않음.
스프링의 객체관리 기본정책은 한번 등록된 빈은 계속 요청해도 만들어줬던것을 계속 내준다.
<bean id="coffee" class="di4.Coffee" scope="prototype"></bean>
getBean해서 얻어갈때마다 새걸로 준다. scope속성을 따로 지정해주지 않으면 singleton으로 된다.
그래서 한번 등록된 빈은 계속 요청해도 만들어줬던것을 계속 내주는것이다.
singleton = 만들어논것 계속 (기본정책)
prototype = 달라고 요청할때 마다 새거
request = 리퀘스트가 새로 생길때마다 새로 생성
session = 세션이 바뀔때마다 새로 생성
출처 : 삼성SDS멀티캠퍼스
강사 : 홍승길
Email : iccack70@gmail.com
'[Spring]' 카테고리의 다른 글
[Spring]11월 9일 초기화메소드와 소멸메소드 지정하는 방법 (0) | 2015.11.10 |
---|---|
[Spring]11월 9일 스프링 설정 파일을 이용한 객체간의 의존관계 설정 (0) | 2015.11.10 |
[Spring]11월 6일 Spring 기초 (0) | 2015.11.09 |
[Spring]11월 6일 Spring (Spring framework) 메이븐을 활용해서 라이브러리 세팅 (0) | 2015.11.09 |
[Spring]11월 6일 Spring framework란, 이클립스에서 스프링 플러그인 설치방법 (0) | 2015.11.09 |