【问题标题】:Cannot get external file properties loaded in Context无法获取在上下文中加载的外部文件属性
【发布时间】:2014-06-12 10:02:42
【问题描述】:

我正在使用 Spring 3.2.9.FINAL 设置一个项目,但我无法加载一些我存储在外部文件中的属性。这就是我的 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 属性。在我的主要方法中,我这样做:

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 的答案尝试了几种解决方法,但似乎没有任何效果。我做错了什么?

【问题讨论】:

  • 能否提供/home/myapp/settings.properties的内容?
  • test.property=Hello world

标签: spring properties-file


【解决方案1】:

您正在将 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());
    }
}

请参阅 the reference guide 了解差异说明。

【讨论】:

  • 成功了。谢了哥们!请从第三行删除额外的变量声明;-)
  • ApplicationContext 不支持延迟加载。 BeanFactory 支持延迟加载。
  • @AmrishPandey 一个ApplicationContextBeanFactory,它在内部使用BeanFactory。你的评论没有意义。
  • 应用程序上下文从spring XML文件加载所有bean并且不支持选择性延迟加载但是使用XML bean工厂版本(检查精确的类名)可以选择性地加载bean。请测试。
  • @AmrishPandey 不,它没有,如上所述,你所说的没有意义......
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2016-09-02
    • 2011-08-27
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2014-12-30
    相关资源
    最近更新 更多