beans.xml 파일을 수정해보자.
1 2 3 4 5 6 7 8 9 10
| <?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="koreanTire" class="KoreanTire"/> <bean id="americanTire" class="AmericanTire"/> <bean id="car" class="Car"> <property name="tire2" ref="koreanTire"/> </bean> </beans>
|
beans의 property는 getter/setter와 매핑이 된다.
Car.java를 수정해보자.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Car { private Tire tire; public Car() {} public Car(Tire tire) { this.tire = tire; } public Tire getTire2() { return tire; } public void setTire2(Tire tire) { this.tire = tire; } }
|
Driver.java를 수정해보자.
1 2 3 4 5 6 7 8 9 10 11 12
| import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Driver { public static void main(String[] args) { ApplicationContext context = new FileSystemXmlApplicationContext("/src/beans.xml"); Car car = (Car)context.getBean("car");
car.getTire2().wheel(); } }
|
property를 지정했기 때문에 koreanTire가 DI됐다.
참조 블로그 - 스프링을 통한 의존성 주입 - 스프링 설정 파일(xml)에서 속성 주입