属性占位符配置器从XML文件中读取(Apache Commons Configuration)

4
有没有可能配置Spring PropertyPlaceholderConfigurer从properties.xml中读取,通过Apache Commons Configuration?

3个回答

3

seanizerspringmodule 的帮助下,我找到了解决方案。

<!-- 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一起使用。

请随意复制并粘贴!


2

最简单的方法(虽然可能不是最好的)是继承PropertyPlaceholderConfigurer类,加载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>

3
或许你可以详细说明“它不起作用”的原因。毕竟,达夫已经花了一些时间尝试回答你的问题。 - Sean Patrick Floyd
1
没错,这不应该是一个复制粘贴的答案(我必须假设你在回复中没有提供有用的信息并且给了无解释的踩)。像往常一样,这只是一个解决问题的指南,如果你有具体的问题,请在回复中提出。 - Daff
2
对不起,我之前的评论很恶劣,你让我找到了正确的方向! - Alex

1

这里有一个使用Spring模块的解决方案。我不知道它有多新,但即使它不是最新版本,你也可以很容易地拿到代码并让它与当前版本一起工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接