2016년 8월 8일 월요일

[방학특강,IT실무교육,스프링학원추천☆탑크리에듀]#16.SpEL을 이용한 Value Injection(XML 방식)



SpEL 이용한 Value Injection(XML 방식)

<!--[if !supportLists]-->n  <!--[endif]-->Spring 3.X에서 추가된 기능으로 SpEL을 이용하면 동적으로 표현식을 해석하고 그 결과를 Spring ApplicationContext에서 사용할 수 있다. 결국 동적으로 생성된 값을 다른 자바 빈에 주입할 수 있다.

[app-context2.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-4.2.xsd">
<bean name="onj" class="onj.spel.injection.Onj"/>
<bean name="sample" class="onj.spel.injection.SpelInjectionExam">
<property name="name">
           <value>#{onj.name}</value> 
        <!--  Onj 클래스에는 Getter가 만들어져 있어야 한다. -->
</property>
<property name="age">
           <value>#{onj.age}</value>
</property>
</beans>


[Onj.java]
package onj.spel.injection;
public class Onj {

    private String name="OnJ";
    private String age = "10";
/*
app-context2.xml에서 SpelInjectionExam 에 값을 주입하기 위해 getter만 만듬
#{onj.name} 구문에 의해 getter가 호출되고 그 값이 SpelInjectionExam에 주입된다.
*/
    public String getName() {
        return name;
    }

    public String getAge() {
        return age;
    }

}

[SpelInjectionExam.java]
package onj.spel.injection;

import org.springframework.context.support.GenericXmlApplicationContext;

public class SpelInjectionExam {
private String name;
private String age;

// 빈 정의 XML에서 name이라는 Property value 값을 주입 받음
public void setName(String name) {
this.name = name;
}

// 빈 정의 XML에서 age라는 Property value 값을 주입 받음
public void setAge(String age) {
this.age = age;
}

public String toString() {
return "This is spel injection example... " +
           "Your name is " + name + " age is " + age;
}

public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:app-context2.xml");
ctx.refresh();

SpelInjectionExam sample = (SpelInjectionExam) ctx.getBean("sample");
System.out.println(sample);
}
}

[결과]
This is spel injection example... Your name is OnJ age is 10


댓글 없음:

댓글 쓰기