Framework/Spring
[Spring] SpEL을 사용한 Spring Properties 사용방법 / properties 설정
나비와꽃기린
2016. 8. 17. 09:48
1. 정의 지정
<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"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
2. properties파일 지정
id에 지정된 값은 config라는 이름으로 사용하겠다는 뜻이다.
사용할 properties의 path를 적어준다.
<util:properties id="config" location="classpath:/config/config.properties" />
3. 사용방법
(1) xml에서 사용방법
#{config['jndiName']} 는 config 라는 id에 해당하는 properties의 jndiName으로 지정되어있는 값을 가져와서 사용하겠다는 의미이다.
<!-- 데이타 소스 -->
<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="#{config['jndiName']}" />
</bean>
이때 해당 config.properties 파일에는 다음과 같이 K V 형식으로 작성해주면 된다.
그럼 jndiName에 매핑되어져 있는 jdbc/XXXX값을 가져와 사용하게 된다.
# 데이터 소스 jndiName=jdbc/XXXX |
(2) java class에서 사용방법
@Value("#{cofig['properties파일에 설정했던 key값 입력']}") 으로 사용.
import org.springframework.beans.factory.annotation.Value;
@Controller
public class TestController {
@Value("#{config['jndiName']}") String xxx;
public static void main(String[] args) {
System.out.println( xxx );
}
}