BeanWiring 의 정의
- 스프링은 객체가 자신의 일을 하기 위해서 다른 객체를 직접 찾거나 생성할 필요가 없다.
- 컨테이너가 협업할 객체를 직접 제공한다.
- 이러한 객체간의 연관관계 형성 작업이 종속객체 주입(DI) 이를 와이링이라고 한다.
빈 선언
인터페이스 구현
public interface Performer {
public void perform() throws PerformanceException;
}
예외처리 클래스
- Exception 을 상속받는 PerformanceException
- 어떤 예외가 올 지 모르기 때문에 모든 예외를 처리해주는 Exception을 사용
public class PerformanceException extends Exception {
}
메인 클래스
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class BeanWiringTest {
public static void main( String[] args ) throws PerformanceException {
ApplicationContext ctx
= new ClassPathXmlApplicationContext( "/wiring/bean/ApplicationContext.xml" );
Performer hong = (Performer) ctx.getBean( "hong" );
hong.perform();
Performer singer = (Performer) ctx.getBean( "singer" );
singer.perform();
}
}
빈 선언
- Performer(공연자)를 상속받는 Juggler(저글링하는 공연자) 클래스 생성
public class Juggler implements Performer {
private int beanBags = 3;
public Juggler() {}
public Juggler( int beanBags ) {
this.beanBags = beanBags;
}
public void perform() throws PerformanceException {
System.out.println( beanBags + "개를 저글링합니다." );
}
}
- Performer(공연자)를 상속받는 Singer(가수) 클래스 생성
public class Singer implements Performer {
private String name;
private Song song;
public Singer() {}
public Singer(String name, Song song) {
this.name = name;
this.song = song;
}
public void perform() throws PerformanceException {
song.singing();
System.out.println(name);
}
}
- Performer를 상속받는 Juggler를 상속받는 PoeticJuggler 클래스
public class PoeticJuggler extends Juggler {
private Poem poem;
public PoeticJuggler() {}
public PoeticJuggler( int beanBags, Poem poem ) {
super( beanBags );
this.poem = poem;
}
public void perform() throws PerformanceException {
super.perform();
poem.recite();
}
}
객체 주입
생성자를 이용한 주입
<bean id="lee" class="wiring.bean.Juggler"/>
<bean id="park" class="wiring.bean.Juggler">
<constructor-arg value="5"/>
</bean>
<bean id="flower" class="wiring.bean.Flower"/>
<bean id="picnic" class="wiring.bean.Picnic"/>
<bean id="hong" class="wiring.bean.PoeticJuggler">
<constructor-arg value="7"/>
<constructor-arg ref="flower"/>
</bean>
<bean id ="hello" class="wiring.bean.Hello"/>
<bean id="singer" class="wiring.bean.Singer">
<constructor-arg value ="조용필"/>
<constructor-arg ref ="hello"/>
</bean>
객체 레퍼런스 주입
시낭송 인터페이스
package wiring.bean;
public interface Poem {
public void recite();
}
Song(노래) 인터페이스
public interface Song {
public void singing();
}
주입할 객체
- Poem(시) 인터페이스를 상속받은 Flower 클래스
public class Flower implements Poem {
String str = "내가 그의 이름을 불러주기 전에는\r\n" +
"그는 다만\r\n" +
"하나의 몸짓에 지나지 않았다.\r\n";
public void recite() {
System.out.println( "Flower : " + str );
}
}
- Song(노래) 인터페이스를 상속받는 Hello 클래스
public class Hello implements Song {
private String str = "네 눈빛을 보면 꽤 낯 가려 보여\r\n" +
"자존심도 좋지만 난 너 생각뿐야\r\n" +
"Ah~ 손끝만 스쳐도 그댄 벌써 나를 알아보리\r\n" +
"Ah~ 우린 운명이라고 나의 느낌이 말해주지";
public void singing() {
System.out.println( "Hello : " + str );
}
}