복붙노트

[SPRING] .properties 파일의 속성을 기반으로 Spring 설정 파일을 가져옵니다.

SPRING

.properties 파일의 속성을 기반으로 Spring 설정 파일을 가져옵니다.

내 봄 xml 구성에서 작동하도록 뭔가를 얻으려고 노력하고있어 :

<beans>

   <import resource="${file.to.import}" />

   <!-- Other bean definitions -->

</beans>

속성 파일의 속성을 기반으로 가져올 파일을 결정하고 싶습니다. System 속성을 사용할 수는 있지만 시작시 JVM에 속성을 추가 할 수 없다는 것을 알고 있습니다.

참고 : PropertyPlaceHolderConfigurer는 작동하지 않습니다. 가져 오기는 BeanFactoryPostProcessors가 실행되기 전에 해결됩니다. import 요소는 System.properties 만 해결할 수 있습니다.

누구든지 이것에 간단한 해결책이 있습니까? 나는 프레임 워크 클래스를 서브 클래 싱하기 시작하고 싶지 않다.

감사

해결법

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

    1.불행히도, 이것은해야 할 것보다 훨씬 더 어렵습니다. 내 응용 프로그램에서 나는 다음을 수행하여 이것을 수행했다.

    불행히도, 이것은해야 할 것보다 훨씬 더 어렵습니다. 내 응용 프로그램에서 나는 다음을 수행하여 이것을 수행했다.

    이는 컨텍스트 파일이로드 할 책임이있는 bean의 입력으로 지정되기 때문에 작동합니다. 언급 한 것처럼 가져 오기를 시도하면 작동하지 않지만 약간 더 많은 작업을하면 같은 효과가 있습니다. 부트 스트랩 클래스는 다음과 같이 보입니다.

     public class Bootstrapper implements ApplicationContextAware, InitializingBean {
    
        private WebApplicationContext context;
        private String[] configLocations;
        private String[] testConfigLocations;
        private boolean loadTestConfigurations;
    
        public void setConfigLocations(final String[] configLocations) {
            this.configLocations = configLocations;
        }
    
        public void setTestConfigLocations(final String[] testConfigLocations) {
            this.testConfigLocations = testConfigLocations;
        }
    
        public void setLoadTestConfigurations(final boolean loadTestConfigurations) {
            this.loadTestConfigurations = loadTestConfigurations;
        }
    
        @Override
        public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
            context = (WebApplicationContext) applicationContext;
        }
    
        @Override
        public void afterPropertiesSet() throws Exception {
            String[] configsToLoad = configLocations;
    
            if (loadTestConfigurations) {
                configsToLoad = new String[configLocations.length + testConfigLocations.length];
                arraycopy(configLocations, 0, configsToLoad, 0, configLocations.length);
                arraycopy(testConfigLocations, 0, configsToLoad, configLocations.length, testConfigLocations.length);
            }
    
            context.setConfigLocations(configsToLoad);
            context.refresh();
        }
    }
    

    기본적으로 응용 프로그램 컨텍스트를 가져 와서 구성 위치를 설정하고 자체를 새로 고치라고 지시하십시오. 이것은 내 응용 프로그램에서 완벽하게 작동합니다.

    희망이 도움이됩니다.

  2. ==============================

    2.Spring 2.5와 3.0의 경우, 저는 Louis와 비슷한 솔루션을 가지고 있습니다.하지만 앞으로 출시 될 3.1의 특징을 읽어 보았습니다. 자산 관리도 훌륭하게 들립니다.

    Spring 2.5와 3.0의 경우, 저는 Louis와 비슷한 솔루션을 가지고 있습니다.하지만 앞으로 출시 될 3.1의 특징을 읽어 보았습니다. 자산 관리도 훌륭하게 들립니다.

  3. ==============================

    3.Spring JIRA에는 "Will not Fix"로 해결 된 import (SPR-1358)에 대한 속성 자리 표시 자 지원을 추가하는 문제가 있지만 EagerPropertyPlaceholderConfigurer를 사용하여 제안 된 솔루션이 있습니다.

    Spring JIRA에는 "Will not Fix"로 해결 된 import (SPR-1358)에 대한 속성 자리 표시 자 지원을 추가하는 문제가 있지만 EagerPropertyPlaceholderConfigurer를 사용하여 제안 된 솔루션이 있습니다.

    나는 SPR-1358을 재개하기 위해 로비했지만 지금까지는 아무런 반응도 보이지 않았다. 아마도 다른 사람들이 사용 사례를 이슈 발언에 추가하여 인지도를 높이는 데 도움이 될 수 있습니다.

  4. ==============================

    4.왜 안돼 :

    왜 안돼 :

    따라서 현재 제안 된 솔루션을 효과적으로 뒤집을 수 있습니다.

  5. ==============================

    5.다음과 유사한 내용을 추가하십시오.

    다음과 유사한 내용을 추가하십시오.

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="ignoreResourceNotFound"><value>true</value></property>
        <property name="locations">
            <list>
                <value>classpath:propertyfile.properties</value>
            </list>
        </property>
    </bean>
    
  6. ==============================

    6.원하는 경우 applicationContext.xml 외부에서 가져온 XML 파일 이름을 지정하여 가져온 XML 파일 경로의 구성을 손실하지 않고 applicationContext.xml을 바꿀 수 있도록 중간 스프링 bean XML 파일 (예 : confSelector)을 추가하면됩니다. applicationContext.xml은 confSelector.xml을 가져오고 confSelector.xml에는 적합한 사용자 정의 beans XML 파일을 참조하는 요소 만 포함됩니다.

    원하는 경우 applicationContext.xml 외부에서 가져온 XML 파일 이름을 지정하여 가져온 XML 파일 경로의 구성을 손실하지 않고 applicationContext.xml을 바꿀 수 있도록 중간 스프링 bean XML 파일 (예 : confSelector)을 추가하면됩니다. applicationContext.xml은 confSelector.xml을 가져오고 confSelector.xml에는 적합한 사용자 정의 beans XML 파일을 참조하는 요소 만 포함됩니다.

    XML 엔티티 ( 요소를 XML 시작 부분의 DTD 선언에 추가하여 정의 됨)가 사용 될 수있는 또 다른 수단이있을 수 있습니다. 이를 통해 다른 파일에서 XML 조각을 가져 와서 XML 파일에 "속성 자리 표시 자"와 같은 기능을 제공 할 수 있습니다.

    이 두 가지 솔루션 중 어느 것도 Java .properties 형식의 구성 파일을 가질 수 없습니다.

  7. ==============================

    7.필자가 부딪친 André Schuster의 답은 내가 내 호스트에서 실행 중인지, Jenkins에 의해 빌드 호스트에서 실행 중인지 또는 "실제"전개에서 실행 중인지에 따라 다른 속성의 표현식을 찾고 싶었던 것과 매우 비슷한 문제를 해결하는 데 도움이되었습니다. . 저는 이것을 했어요:

    필자가 부딪친 André Schuster의 답은 내가 내 호스트에서 실행 중인지, Jenkins에 의해 빌드 호스트에서 실행 중인지 또는 "실제"전개에서 실행 중인지에 따라 다른 속성의 표현식을 찾고 싶었던 것과 매우 비슷한 문제를 해결하는 데 도움이되었습니다. . 저는 이것을 했어요:

    <context:property-placeholder location="file:///etc/myplace/database.properties" />
    

    나중에

    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>WEB-INF/classes/resources/database.properties</value>
                ...
            </list>
        </property>
    </bean>
    

    내 개발 호스트에서 /etc/myplace/database.properties에 database.properties의 사본을 만들고 Jenkins를 실행하는 서버에 약간 다른 링크가 있기 때문에 문제가 해결되었습니다. 실제 배포에서는 그러한 파일이 발견되지 않으므로 Spring은 클래스 파일의 하위 디렉토리에있는 자원의 "실제"파일로 돌아갑니다. 해당 등록 정보가 /etc/myplace/database.properties에있는 파일에 의해 이미 지정된 경우 (다행스럽게도) 로컬 파일에 의해 다시 정의되지 않습니다.

  8. ==============================

    8.시스템 속성에 의존하지 않는 또 다른 해결 방법은 각 파일에 대해 다른 PropertyPlaceholderConfigurer를 사용하여 모든 파일의 속성을로드하고 각각에 대해 다른 자리 표시 자 접두사를 정의하는 것입니다. 그 placeholderprefix는 초기 등록 정보 파일에 의해 구성됩니다.

    시스템 속성에 의존하지 않는 또 다른 해결 방법은 각 파일에 대해 다른 PropertyPlaceholderConfigurer를 사용하여 모든 파일의 속성을로드하고 각각에 대해 다른 자리 표시 자 접두사를 정의하는 것입니다. 그 placeholderprefix는 초기 등록 정보 파일에 의해 구성됩니다.

    첫 번째 특성 파일을 정의하십시오 (첫 번째 또는 두 번째 포함).

    fileToUse=first
    

    위에서 정의한 속성에 따라 전환 할 수있는 속성을 포함하는 파일을 정의합니다.

    aProperty=propertyContentOfFirst
    
    aProperty=propertyContentOfSecond
    

    그런 다음 모든 파일의 자리 표시자를 정의하십시오.

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:global.properties</value>
            </list>
        </property>
    </bean>
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="placeholderPrefix" value="first{" />
        <property name="locations">
            <list>
                <value>classpath:first.properties</value>
            </list>
        </property>
    </bean>
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="placeholderPrefix" value="second{" />
        <property name="locations">
            <list>
                <value>classpath:second.properties</value>
            </list>
        </property>
    </bean>
    

    전역에 정의 된 등록 정보를 사용하여 다른 파일에서 사용할 자원을 식별하십시오.

    ${fileToUse}{aProperty}
    
  9. ==============================

    9.아래에 JVM 인자를 추가하고 myApplicationContext.dev.xml 파일을 가지고 있다면 스프링이로드됩니다.

    아래에 JVM 인자를 추가하고 myApplicationContext.dev.xml 파일을 가지고 있다면 스프링이로드됩니다.

    DmyEnvironment = dev

    <context:property-placeholder />
    
    <import resource="classpath:/resources/spring/myApplicationContext.${myEnvironment}.xml"/>
    
  10. ==============================

    10.나는 스프링 3을 사용하고 다음과 같은 속성을로드한다.

    나는 스프링 3을 사용하고 다음과 같은 속성을로드한다.

    <context:property-placeholder location="/WEB-INF/my.properties" />
    
  11. from https://stackoverflow.com/questions/1520055/import-spring-config-file-based-on-property-in-properties-file by cc-by-sa and MIT license