2013년 7월 23일 화요일

[오라클자바개발자실무교육,오엔제이프로그래밍실무교육센터,SpringFremawork3강좌]Spring IoC Ref로 빈 주입하기

-      하나의 빈을 다른 빈에 주입하기 위해 설정하려면 두 개의 빈 설정 필요
-       하나의 빈은 주입될 빈이고, 다른 빈은 타겟이 되는 빈이다.
-       주입될 빈과 타겟에서 setter로 정의한 빈은 서로 호환이 되기만 하면 된다.
  (예를 들면 타겟에서 정의한 빈이 인터페이스이면 주입될 빈은 인터페이스를 구현한 클래스면 된다는 것이다)
- 빈 정의는 같은 XML 파일 내에 있어야 한다. 만약 다른 이름의 빈을 주입하거나 다른 설정파일에서 빈을 찾으려면 <ref> 태그의 bean 속성을 사용해야 한다.
-       ref태그를 사용하여 주입하며 ref태그는 항상 property constructor-arg 다음에 나와야 한다


오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷  실무전문 강의)

u  app-context4.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">
       <bean id="onj" name="onjName" class="onj.ref.injection.Onj"/>
       <bean id="sample" name="sampleName" class="onj.ref.injection.RefInjectionExam">
             <property name="onj">
                    <ref local="onj"/> <!--  ref 태그는 빈의 id 빈을 찾는다 -->
             </property>        
       </bean>
</beans>
u  Onj.java
package onj.ref.injection;
public class Onj {
       private String name="OnJ";
       private String age = "10";
       public String getName() {
             return name;
       }
      
       public String getAge() {
             return age;
       }     
}
u  RefInjectionExam.java
package onj.ref.injection;
import org.springframework.context.support.GenericXmlApplicationContext;
public class RefInjectionExam {
       private Onj onj;          
       public void setOnj(Onj onj) {
             this.onj = onj;
       }
      
       public String toString() {
             return "This is ref injection example... " +
                  "Your name is " + onj.getName() + ", age is " + onj.getAge();
       }
       public static void main(String[] args) {
             GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
             ctx.load("classpath:app-context4.xml");
             ctx.refresh();
             RefInjectionExam sample = (RefInjectionExam) ctx.getBean("sample");
             System.out.println(sample);
       }
}
[결과]
This is ref injection example... Your name is OnJ, age is 10

댓글 없음:

댓글 쓰기