복붙노트

[SPRING] Spring 컨텍스트에서 기본 경로로 시스템 속성에서 속성 파일로드

SPRING

Spring 컨텍스트에서 기본 경로로 시스템 속성에서 속성 파일로드

내 봄 컨텍스트에서 시스템 속성에서 오는 경로로 속성 파일 (전쟁 외부에 위치)을로드하려고합니다.

해당 시스템 속성이 없거나 경로를 찾을 수없는 경우 내 .war에 포함 된 기본 속성 파일로 폴백하고 싶습니다.

내 applicationContext.xml의 특정 부분은 다음과 같습니다.

<context:property-placeholder ignore-resource-not-found="true" ignore-unresolvable="true" location="file:${config.dir}/config/server.properties"/>
<context:property-placeholder ignore-resource-not-found="false" location="classpath:config/server.properties"/>

문제는 config.dir이 시스템 속성에서 발견되지 않으면 확인자가 해당 속성을 찾지 못했다는 것을 나타내는 예외가 발생한다는 것입니다.

그리고 해결할 수있는 경우조차도 두 번째 줄은 매개 변수에 주어진 파일에로드 된 속성이 기본 파일에있는 속성으로 바뀌도록하고 싶습니다. 이는 내가 원하는 것과 반대입니다 .

나는 XML 전용 구성으로 Spring 4.x를 사용하고있다.

내가 원하는 걸 할 수 있을까? Java 기반 구성에 대한 @ 조건부를 알고 있지만 xml 방식 만 사용하여 프로젝트 기준에 응답 할 수 있습니다.

해결법

  1. ==============================

    1.두 개의 자리 표시자를 사용하지 않고 하나만 사용하고 location 속성은로드 할 파일 목록을 구분합니다.

    두 개의 자리 표시자를 사용하지 않고 하나만 사용하고 location 속성은로드 할 파일 목록을 구분합니다.

    <context:property-placeholder ignore-resource-not-found="true" location="file:${config.dir}/config/server.properties,classpath:config/server.properties"/>
    

    그러나 config.dirproperty를 사용할 수 있어야합니다. 그렇지 않으면로드가 폭발합니다.

    또 다른 해결책은 ApplicationContextInitializer를 사용하고 config.dir 속성로드의 가용성에 따라 추가 파일을로드하는 것입니다.

    public class ConfigInitializer implements ApplicationContextInitializer {
    
        public void initialize(ConfigurableApplicationContext applicationContext) {
            ConfigurableEnvironment env = applicationContext.getEnvironment();
            MutablePropertySources mps = env.getPropertySources();
    
            mps.addLast(new ResourcePropertySource("server.properties", "classpath:config/server.properties"));
    
            if (env.containsProperty("config.dir")) {
                String configFile = env.getProperty("config.dir")+"/config/server.properties";
                Resource resource = applicationContext.getResource(configFile);
                if (resource.exists() ) {
                    mps.addBefore("server.properties", new ResourcePropertySource(resource));
                }
            }
        }
    }
    

    이제 빈 요소 만 필요합니다.

    추가 된 이점은 기본 등록 정보에 기본 config.dir을 지정하고 시스템 또는 환경 등록 정보로 대체 할 수 있다는 것입니다.

  2. from https://stackoverflow.com/questions/30640453/loading-property-file-from-system-properties-with-default-path-in-spring-context by cc-by-sa and MIT license