SpEL을
이용한 value
Injection(annotation 방식)
오라클자바커뮤니티에서 설립한
오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝,
힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의)
- Spring 3.X에서
추가된 기능
- Value 애노테이션에서 SpEL을 기술하면 된다
u app-context3.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.springframe
work.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="onj.spel.annotation" />
</beans>
u Onj.java
package onj.spel.annotation;
import org.springframework.stereotype.Component;
/*
@Service대신
@Component를
사용했다. 효과는
동일
애노테이션
기반의
설정과
스캔을
스프링에게
자동감지하도록
명령
Onj 클래스는
비지니스서비스
보다는
설정을
저장하는
DTO형태이므로
@Component가
적합
*/
@Component("onj")
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;
}
}
u SpelInjectionExam.java
package onj.spel.annotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import
org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.stereotype.Service;
@Service("sample")
public class SpelInjectionExam {
private String name;
private String age;
/* Onj객체의
getName을
호출해
값을
세팅 */
@Value("#{onj.name}")
public void setName(String name) {
this.name = name;
}
/* Onj객체의
getAge를
호출해
값을
세팅 */
@Value("#{onj.age}")
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-context3.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
댓글 없음:
댓글 쓰기