无法在上下文中加载外部文件属性



我正在使用Spring 3.2.9建立一个项目。最后,我只是无法加载一些属性,我已经存储在一个外部文件。这就是我的application-context.xml的样子:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/util 
        http://www.springframework.org/schema/util/spring-util-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    <context:property-placeholder
        location="file:/home/myapp/settings.properties" />
    <bean class="foo.Test">
        <property name="property" value="${test.property}" />
    </bean>
</beans>

这是我的settings.properties文件的内容:

test.property=Hello world

foo.Test类非常简单,只包含一个String属性。在main方法中,我这样做:

public class App {
    public static void main(String[] args) {
        DefaultListableBeanFactory dlbf = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(dlbf);
        reader.loadBeanDefinitions(new ClassPathResource(
                "/application-context.xml", Test.class));
        System.out.println(dlbf.getBean(Test.class).getProperty());
    }
}

这是我执行它时得到的结果:

Jun 12, 2014 12:03:38 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [application-context.xml]
${test.property}

我尝试了几种基于SO的答案的解决方案,但似乎没有任何作用。我做错了什么?

您正在加载bean到BeanFactory中,而您应该使用ApplicationContext

public class App {
    public static void main(String[] args) {
        ApplicationContext ctx d= new ClassPathXmlApplicationContext("application-context.xml");
        System.out.println(ctx.getBean(Test.class).getProperty());
    }
}

应用程序上下文从spring XML文件加载所有bean,并且不支持选择性延迟加载,但是使用XML bean工厂版本(检查精确的类名)可以选择性地加载bean。请测试。

最新更新