Spring IoC 생성자 주입(Constructor Injection)을 Annotation기반으로 이용하여 만들어 보자.
오라클자바커뮤니티에서 설립한
오엔제이프로그래밍 실무교육센터
(오라클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/>
<context:component-scan base-package="onj.spring.di2" />
</beans>
<!--[if !supportLists]-->2.
<!--[endif]-->CarMaker.java
package onj.spring.di2;
public
interface CarMaker {
public
Car sell();
}
<!--[if !supportLists]-->3.
<!--[endif]-->Audi.java
package onj.spring.di2;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.stereotype.Service;
//자바코드에서
주입될
빈이라고
정의함. XML파일에서 "sudi"정의안해도됨
@Service("audi")
public
class
Audi implements CarMaker {
private Car car;
@Autowired //빈
생성시
자동
엮임
public
Audi(Car car) {
this.car =
car;
}
public
Car sell() {
this.car.setName("Audi A6");
return
car;
}
}
<!--[if !supportLists]-->4.
<!--[endif]-->Car.java
package onj.spring.di2;
import
org.springframework.stereotype.Service;
//Audi에
주입될
클래스이므로 car 라는
이름으로 XML 파일에서
빈정의함
@Service("car")
public
class
Car {
private String name;
public
Car() {
}
public
String getName() {
return
this.name;
}
public
void
setName(String name) {
this.name =
name;
}
}
<!--[if !supportLists]-->5.
<!--[endif]-->ConstructorInjectionExam.java
package onj.spring.di2;
import
org.springframework.context.support.GenericXmlApplicationContext;
public
class
ConstructorInjectionExam
{
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());
}
}
<!--[if !supportLists]-->6.
<!--[endif]-->[결과]
I
sold a car... Audi A6
댓글 없음:
댓글 쓰기