- Engine.java 생성
package kr.or.connect.diexam01;
public class Engine {
public Engine() {
System.out.println("Engine 생성자");
}
public void exec() {
System.out.println("엔진이 동작합니다.");
}
}
- Car.java 생성
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();
}
}
- applicationContext.xml 수정
<?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 ="userBean" class="kr.or.connect.diexam01.UserBean"/>
<bean id = "e" class="kr.or.connect.diexam01.Engine"/>
<bean id = "c" class="kr.or.connect.diexam01.Car">
<property name="engine" ref="e"></property>
</bean>
</beans>
- ApplicationContextExam02.java 생성
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("classpath:applicationContext.xml");
Car car = (Car)ac.getBean("c");
car.run();
}
}
- 결과
생각해 보기