4

Apache Commons Configurationを介してproperties.xmlから読み取るようにSpringPropertyPlaceholderConfigurerを構成する可能性はありますか?

4

3 に答える 3

3

seaizerspringmoduleの助けを借りて解決策を見つけました

<!-- Composite configuration -->
<bean id="configuration" class="org.springmodules.commons.configuration.CommonsConfigurationFactoryBean">
    <property name="configurations">
        <list>
            <!-- User specifics -->
            <bean class="org.apache.commons.configuration.XMLConfiguration">
                <constructor-arg type="java.net.URL" value="file:cfg.xml" />
            </bean>
        </list>
    </property>
</bean>

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="properties" ref="configuration"/>
</bean>

<bean id="testConfig" class="uvst.cfg.TestConfiguration">
    <property name="domain" value="${some.prop}"></property>
</bean>

クラス TestConfiguration

public class TestConfiguration {
    private String domain;
    public String getDomain() {
        return domain;
    }
    public void setDomain(String domain) {
        this.domain = domain;
    }
}

jUnit テストクラス

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration( { "/applicationContextTest.xml" })

public class ApacheCommonCfg2Spring extends AbstractJUnit4SpringContextTests {

    private TestConfiguration tcfg;

    @Test
    public void configuration(){
        tcfg  = this.applicationContext.getBean("testConfig", TestConfiguration.class);
        System.out.println(tcfg.getDomain());
    }

}

Springmodule はかなり古いため、メンテナンスされていないようですが、Spring 3.0.3 で動作します。

自由にコピー&ペーストしてください!

于 2010-07-06T08:26:29.483 に答える
2

最も簡単な方法 (あまり良い方法ではないかもしれません) は、PropertyPlaceholdeConfigurer をサブクラス化し、そこに Commons 構成をロードして、それをスーパークラスに渡すことです。

public class TestPlaceholderConfigurer extends PropertyPlaceholderConfigurer
{
    public TestPlaceholderConfigurer()
    {
        super();
    }

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
            throws BeansException
    {
        XMLConfiguration config = new XMLConfiguration("config.xml");
        Properties commonsProperties = config.getProperties("someKey")
        // Or something else with the configuration
        super.processProperties(beanFactoryToProcess, commonsProperties);
    }
}

次に、このクラスを placeholderConfig として使用します。

<bean id="placeholderConfig"
    class="com.exampl.TestPlaceholderConfigurer ">
    <!-- ... -->
</bean>
于 2010-07-02T07:42:16.233 に答える
1

これはspring modules を使用したソリューションです。これがどれほど最新のものかはわかりませんが、そうでない場合でも、おそらくコードを簡単に取得して、現在のバージョンで動作させることができます.

于 2010-07-02T12:26:06.817 に答える