프로젝트를 진행하다보면 파일안에 Properties 파일들을 저장해놓고 사용하는 일들이 자주 생긴다. 

가장 간단하게 사용하는 방법은 XML 혹은 JSON을 특정 경로에 넣고 파싱하는 방법이 있으나 설정파일을 사용하는 곳이 많아질 경우 복잡하다. 

스프링 프레임워크는 프레임워크 단에서 Properties 를 설정하는 방법을 가지고 있다.


Spring 설정 xml 안에 아래와 같은 설정을 추가한다. 

<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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.2.xsd">
	<context:component-scan base-package="com.tutorialspoint" />

	 <!-- context:property-placeholder location="classpath:database.properties"  /!-->
	<context:property-placeholder location="/WEB-INF/*.properties" />

</beans>


그럼 자동으로 WEB-INF 경로 아래에 있는 *.properties 밸류들이 로드된다.


스프링 내에서 사용하기 위해선 아래와 같이 사용한다.

@Component
class MyClass {
  @Value("${my.property.name}")
  private String[] myValues;
}


만약 위의 설정 방법이 안된다면 수동으로 빈을 생성해준다. 


<bean id="myProperties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath*:my.properties</value>
    </list>
  </property>
</bean>

그리고 Resource 파일을 이용해서 불러들인다. 

@Component
class MyClass {
  @Resource(name="myProperties")
  private Properties myProperties;

  @PostConstruct
  public void init() {
    // do whatever you need with properties
  }
}



* 추가 

Project 진행시에 보통 개발, 테스트, 프로덕션 서버별로 배포를 다르게한다. 

각각의 환경마다 다른 설정값을 가지므로 배포시마다 사용하는 property 의 이름을 변경해주는 것은 여간 귀찮은 일이 아니다

다행이 스프링에서는 Profile 이라고 환경마다 다른 설정을 사용할수 있는 기능이 이미 내장되어있다. 

경로 부분을 지정해주고 ${spring.profiles.active} 코드를 넣어주면 Profile에 따라 설정값이 다르게 쓰인다. 

아래는 예제코드를 보면 profile 을 사용하시는 분들이라면 바로 이해가 갈것이다. 

<context:property-placeholder location="classpath:${spring.profiles.active}.properties" />



참고: 

1. http://jijs.tistory.com/entry/spring-%EC%84%A4%EC%A0%95-xml%EA%B3%BC-%EC%86%8C%EC%8A%A4%EC%BD%94%EB%93%9C%EC%97%90%EC%84%9C-properties-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0

2. http://stackoverflow.com/questions/9259819/how-to-read-values-from-properties-file

3. http://nkjava.blogspot.kr/2013/07/springmvc-read-property-in-jsp.html

4. http://stackoverflow.com/questions/10669474/load-properties-file-in-spring-depending-on-profile

+ Recent posts