본문 바로가기

TroubleShooting/Spring

jar 파일 외부에서 프로퍼티 이용하는 방법(spring)

728x90

Spring jar 를 실행할때, config 파일을 jar 외부에서 수정할 수 있도록 하는 방법


src/main/resources 디렉토리에 스프링 콘텍스트 파일인 app-context.xml 에서 app-properties.xml 이라는 프로퍼티(보통 이 파일안에는 DB 연결할때의 서버 IP 나 로그인 ID/패스워드가 있다.) 파일을 읽어서 프로그램 관련 설정을 가지고 올때, jar 로 묶으면 jar 파일에 함께 들어가기 때문에 app-properties.xml 파일을 수정할 수가 없는 상황이 된다.


<app-context.xml>

<util:properties id="data" location="classpath:app-properties.xml" />


...


<property name="jdbcUrl" value="#{data['url']}" />

<property name="user" value="#{data['username']}" />

<property name="password" value="#{data['password']}" />


해결 방법을 찾아보니, location 을 locatons 로 바꾸고 list 형태로 설정 파일 위치를 지정하라고 해서 추가해봤는데 팩토리 생성 빈이라 설정 위치를 찾을 수 없다는 에러메시지가 나왔다.
        <property name="locations">
            <list>
                <value>classpath:app-properties.xml</value>
                <value>${propertyPath}/app-properties.xml</value>
            </list>
        </property>

해결방법은 util:properties
(org.springframework.beans.factory.config.PropertiesFactoryBean) 팩토리 생성 빈과 ProperyPlaceholderConfigurer 를 함께 사용하는 것이다.

<context:property-placeholder properties-ref="data" />
<bean id="data" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:app-properties.xml</value>
                <value>${propertyPath}/app-properties.xml</value>
            </list>
        </property>
        <property name="ignoreResourceNotFound" value="true"/>
 </bean>


jar 파일로 실행시에 -D 옵션으로 propertyPath 값을 지정해줘야한다.

java -D propertyPath=file:///aaaa -jar excureApp.jar


참고 :

http://www.summa-tech.com/blog/2009/04/20/6-tips-for-managing-property-files-with-spring