SpEL을 이용한 Value Injection(어노테이션 방식)
[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-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:annotation-config/>
<context:component-scan base-package="onj.spel.annotation" />
</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.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
댓글 없음:
댓글 쓰기