IT_Programming/Dev Libs & Framework

[펌][SPRING] 배포 환경 별 설정 분리하기

JJun ™ 2016. 2. 11. 04:19



 * 출처

 : https://enjoydev.tistory.com/1



프로젝트를 진행해 보면 배포 환경 별로 설정을 분리해야 하는 경우가 많습니다.


예를들어 LOCAL/DEV/PRD 환경 별로 DB 환경이 다를 수도 있겠죠?

이런 경우 설정파일을 분리하고 서버 설정 시 시스템 프로퍼티를 등록하고 


해당 환경에 맞게 설정파일로 실행할 수 있도록 합니다.


예시)

classpath:/config/config-common.properties => 공통 설정 파일

classpath:/config/config-dev.properties => 개발 서버 용 설정 파일

classpath:/config/config-local.properties => 로컬 개발 환경 용 설정 파일

classpath:/config/config-prd.properties => 운영 환경 서버 용 설정 파일


설정하는 방법은 간단합니다. ^^*




1. Spring 설정하기 (web.xml)


Spring 환경은 이미 알고 계시겠지만 아래와 같이 설정하면 됩니다.

Servlet Context 와 기타 설정을 분리해서 설정합니다.


<!-- Start - Spring Configuration -->


<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:/config/spring/context-*.xml</param-value>

</context-param>


<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>


<servlet>

<servlet-name>dispatcher_spring</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/spring/root-context.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>


<servlet-mapping>

<servlet-name>dispatcher_spring</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>


<!-- End - Spring Configuration -->





2. Property 설정 (context-common.xml)


배포 환경 별로 공통 설정은 config-common.peroperties 파일에 설정하고, 기타 배포 환경 별로 분리되어야 하는 설정은 

각 설정 파일에 추가하도록 설정합니다. 프로퍼티 파일의 위치에 따라 동일한 프로퍼티의 값이 달라집니다.


현재 설정은 각 배포 환경 별 설정 파일의 값이 우선 적용되게 됩니다.


만약 공통 프로퍼티의 값을 우선 적용하려면 우선를 변경하세요. ^^*


<!-- 기본 환경설정용 properties 파일을 읽는 설정 -->

<bean id="config"

class="org.springframework.beans.factory.config.PropertiesFactoryBean">

<property name="locations">

<list>

<value>classpath:/config/config-common.properties</value>

<value>classpath:/config/config-#{systemProperties['spring.profiles.active']}.properties

</value>

</list>

</property>

</bean>





3. 서버 환경 별 시스템 프로퍼티 설정하기 (Tomcat 기준)



Tomcat 실행 시 -Dspring.profiles.active=local[dev|stg|prd] 를 설정합니다.



[Eclipse 설정]