Spring IoC 세터주입(Setter
Injection)을 애노테이션을 이용하여 만들어 보자.
오라클자바커뮤니티에서 설립한
오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝,
힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의)
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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<description>Example configuration to get you started.</description>
<context:annotation-config/> <!—코드
기반의
의존성
요구조건이
가능토록
a
<context:component-scan base-package="onj.spring.di" />
</beans>
2.
CarMaker.java
package onj.spring.di;
public
interface CarMaker {
public
Car sell();
}
3.
Audi.java
package onj.spring.di;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.stereotype.Service;
//자바코드에서
주입될
빈이라고
정의함. XML파일에서 "sudi"정의안해도됨
@Service("audi")
public
class
Audi implements CarMaker {
private Car car;
public
Audi() {}
@Autowired //이부분은 @Resource(name="car") 라고
해도
결과는
같
public
void
setCar(Car car) {
this.car =
car;
}
public
Car sell() {
this.car.setName("Audi A6");
return
car;
}
}
4.
Car.java
package onj.spring.di;
import
org.springframework.stereotype.Service;
@Service("car")
//Car클래스가
Audi setCar의
인자로
들어가야
되므로...빈으로
정의되야
한다.
public
class
Car {
private String name;
public
Car() {
}
public
String getName()
{
return
this.name;
}
public
void
setName(String name) {
this.name =
name;
}
}
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());
}
}
6.
[결과]
I sold a car... Audi A6
댓글 없음:
댓글 쓰기