package lunch.service;
public interface Eat {
void eatLunch();
}
package lunch.service.impl;
import lunch.service.Eat;
public class Noodle implements Eat {
@Override
public void eatLunch() {
System.out.println("국수를 먹습니다.");
}
}
package lunch.service.impl;
import lunch.service.Eat;
public class Rice implements Eat {
@Override
public void eatLunch() {
System.out.println("쌀밥을 먹습니다.");
}
}
package lunch;
import lunch.service.Eat;
public class Lunch {
private Eat eat;
public void setEat(Eat eat) {
this.eat = eat;
}
public void haveLunch() {
eat.eatLunch();
}
}
setEat 메서드를 통해 Eat 인터페이스를 주입받고, haveLunch 메서드를 호출하여 Eat 인터페이스의 구현체를 사용합니다.
<?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="noodle" class="lunch.service.impl.Noodle"></bean>
<bean id="rice" class="lunch.service.impl.Rice"></bean>
<bean id="lunch" class="lunch.Lunch">
<property name="eat" ref="rice"></property>
</bean>
</beans>
xml의 ref="rice"를 -> ref="noodle"로 수정하면
실행문이 '국수를 먹습니다'로 바뀝니다.
package lunch;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("config/app.xml");
Lunch lunch = (Lunch) context.getBean("lunch");
lunch.haveLunch();
}
}