package kr.or.connect.diexam01;
public class Engine {
public Engine() {
System.out.println("Engine 생성자");
}
public void exec() {
System.out.println("엔진이 동작합니다.");
}
}
package kr.or.connect.diexam01;
public class Car {
private Engine v8;
public Car() {
System.out.println("Car 생성자");
}
public void setEngine(Engine e) {
this.v8=e;
}
public void run() {
System.out.println("엔진을 이용하여 달립니다.");
v8.exec();
}
public static void main(String[] args) {
Engine e = new Engine();
Car c= new Car();
c.setEngine(e);
c.run();
}
}
Car 객체에서 Engine 객체를 사용하려면 미리 생성하여 set해야 함
-> ApplicationContext로 getBean을 하면 Car객체만 가져와도 따로 Engine 객체 생성할 필요 없이 실행됨
<?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="e" class="kr.or.connect.diexam01.Engine"></bean>
<bean id="c" class="kr.or.connect.diexam01.Car">
<property name="engine" ref="e"></property>
</bean>
</beans>
package kr.or.connect.diexam01;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ApplicationContextExam02 {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// getBean는 Object형식으로 반환하므로 형변환 필수
Car car=(Car) ac.getBean("c");
car.run();
}
}