스프링프레임워크, 주입, Simple Value Injection(@Value, @PropertySource), SpEL을 이용한 Value Injection, . @Value, @PropertySource

스프링프레임워크, 주입, Simple Value Injection(@Value, @PropertySource), SpEL을 이용한 Value Injection, . @Value, @PropertySource2-5-6. Simple Value Injection(@Value, @PropertySource) n 빈 정의 XML 파일에서 property 태그의 v…
ojc.asia
2-5-6. Simple Value Injection(@Value, @PropertySource)
n 빈 정의 XML 파일에서 property 태그의 value 태그로 값을 지정하며 String으로 값을 읽는다.
n property의 value를 주입 받는 빈에서는 setter를 만들어야 한다.
[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="sample" class="onj.value.injection.ValueInjectionExam"> <property name="name"> <value>onj</value> </property> <property name="age"> <value>6</value> </property> </bean> </beans> |
[자바 코드]
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; }
|
2-5-7. SpEL을 이용한 Value Injection(XML 방식)
n 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 |
2-5-8. 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 |
2-5-9. @Value, @PropertySource
n @Value 어노테이션은 Spring의 빈의 필드에 값 자체를 주입하는 데 사용할 수 있으며 멤버필드 또는 생성자 / 메소드 매개 변수 수준에서 적용 할 수 있다.
n @PropertySource 어노테이션은 Spring 3.1 부터 생기기 시작한 통합 프로퍼티 관리 시스템으로 시스템 프로퍼티, 환경변수, JNDI 등을 모두 하나의 공간에 넣고 그 값을 읽고 설정할 수 있게 해준다.
n 다음과 같은 프로퍼티 파일이 있다고 가정하고 @Value에 대해 예문을 살펴보자.
[app.properties] value.from.file=Value got from the file priority=Properties file listOfValues=A,B,C |
n @Value 사용예
@Configuration @PropertySource(“classpath:app.properties”) Class Config { @Value("string value") // “string value” 라는 값자체를 주입 private String name;
@Value("${value.from.file}") // “Value got from the file” 라는 값이 주입 private String valueFromFile;
@Value("${listOfValues}") // “A”, “B”, “C” 라는 문자열 배열이 주입 private String[] valuesArray;
@Value("${java.version}") private String javaVersion;
@Value("#{ systemProperties['user.region'] }") // KR private String defaultLocale;
@Value("#{systemProperties['user.country']}"} String defaultLocale }
만약 XML 기반 스프링 이라면 아래처럼 property placeholer를 지정하면 된다.
<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 <context:component-scan base-package="a.b.sample"/> <context:property-placeholder location="classpath:app.properties"/> </beans>
|
n @Value, @PropertySource 예제 실습
AppConfig
package com.psexam.config;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration @ComponentScan(basePackages = "com.psexam") @PropertySource(value = {"classpath:application.properties"}) public class AppConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceHolderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } } |
AppMain
package com.psexam.main;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.psexam.config.AppConfig; import com.psexam.service.FileService;
public class AppMain { public static void main(String[] args) { AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); //Annotation 방식 //AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("ctx.xml"); //xml방식
FileService svc = (FileService) ctx.getBean("fileService"); svc.readValues(); ctx.close(); } } |
FileService
package com.psexam.service;
public interface FileService { void readValues(); } |
FileServiceImpl
package com.psexam.service;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service;
@Service("fileService") public class FileServiceImpl implements FileService{
@Value("${sourceLocation:c:/tmp/input}") private String source;
@Value("${destinationLocation:c:/tmp/output}") private String destination;
@Autowired private Environment environment;
@Override public void readValues() { System.out.println("Getting property via Spring Environment : " + environment.getProperty("jdbc.driverClassName"));
System.out.println("Source Location :" + source); System.out.println("Destination Location :"+destination); }
} |
src/main/resources/application.properties
jdbc.driverClassName = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3307/mydb jdbc.username = root jdbc.password = 1234 hibernate.dialect = org.hibernate.dialect.MySQLDialect hibernate.show_sql = false hibernate.format_sql = false sourceLocation = /dev/input |
ctx.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan base-package="com.psexam" /> <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> <property name="ignoreUnresolvablePlaceholders" value="true" /> <property name="locations" > <list> <value>classpath:application.properties</value> </list> </property> </bean>
</beans> |
댓글 없음:
댓글 쓰기