Spring IoC의 DI중 하나인 Setter 주입 예제를 만들어 보자.
1. [/src/main/resources/xmlBeanFactory.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="car" class="onj.spring.di.Car"/>
<bean id="audi" class="onj.spring.di.Audi">
<property name="car"><ref bean="car"/></property>
</bean>
</beans>
2. CarMaker.java
package onj.spring.di;
public interface CarMaker {
public Car sell();
}
3. Car.java
package onj.spring.di;
public class Car {
private String name;
public Car() {
}
public Car(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
4. Audi.java(Audi의 setCar 메소드로 Car 인스턴스가 주입된다)
package onj.spring.di;
public class Audi implements CarMaker {
private Car car;
public Audi() {}
public void setCar(Car car) {
this.car = car;
}
public Car sell() {
this.car.setName("Audi A6");
return car;
}
}
5. SetterInjectionExam.java
package onj.spring.di;
import org.springframework.context.support.GenericXmlApplicationContext;
public class SetterInjectionExam {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:xmlBeanFactory.xml");
ctx.refresh();
CarMaker carMaker = ctx.getBean("audi", Audi.class);
Car c = carMaker.sell();
System.out.println("I sold a car... " + c.getName());
}
}
![]() | ![]() ![]() | 12-27 | 2810 | |
![]() | ![]() ![]() | 12-11 | 2043 | |
53 | ![]() ![]() | 03-15 | 1867 | |
52 | ![]() ![]() | 01-31 | 2024 | |
51 | ![]() ![]() | 01-31 | 2988 | |
50 | ![]() ![]() | 01-31 | 1560 | |
49 | ![]() ![]() | 01-19 | 1882 | |
48 | ![]() ![]() | 01-11 | 1756 | |
47 | ![]() ![]() | 01-03 | 2332 | |
46 | ![]() ![]() | 12-27 | 2810 | |
45 | ![]() ![]() | 12-19 | 1969 | |
44 | ![]() ![]() | 12-14 | 1949 | |
43 | ![]() ![]() | 12-11 | 2043 | |
42 | ![]() ![]() | 12-09 | 1589 | |
41 | ![]() ![]() | 12-01 | 1813 | |
40 | ![]() ![]() | 12-01 | 2039 | |
39 | ![]() ![]() | 12-01 | 1465 |
댓글 없음:
댓글 쓰기