【问题标题】:Loading up properties file to a class in Spring在 Spring 中将属性文件加载到类中
【发布时间】:2013-02-23 05:20:23
【问题描述】:

我正在尝试将属性文件 (.properties) 加载到我的类中,我正在关注另一个线程中的示例:How to read values from properties file? - 但它不适合我。

这是我的快速实现:

applicationContext.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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
     http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/tx
     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">


    <context:annotation-config />

    <!-- Load up properties -->
    <context:component-scan base-package="com.test"/>
    <context:property-placeholder location="file:///C:/dev/workspace/test-project/src/main/resources/appconfig.properties"/>
</beans>

TestConfig.java

@Component
public class TestConfig
{

    @Value("${test.key1}")
    private String key1;

    public String getKey1()
    {
        return key1;
    }

}

src/main/resources/appconfig.properties

test.key1=value
test.key2=value

启动我的 tomcat,我在日志中看到以下内容:

00:11:41,985 [localhost-startStop-1]  INFO PropertyPlaceholderConfigurer - Loading properties file from URL [file:/C:/dev/workspace/test-project/src/main/resources/appconfig.properties]

但是,当我执行 getKey1() 时,我得到“null”。

我错过了什么?

问题 2:如果我使用“类路径”:

<context:property-placeholder location="classpath:appconfig.properties"/>

这是指哪个目录? WEB-INF/classes 的根目录?

【问题讨论】:

    标签: spring spring-3


    【解决方案1】:

    我希望你正在使用像 Eclipse 这样的 IDE。

    • 检查资源目录是否已添加到类路径中,并且是否包含其中的所有文件,如果是 eclipse,则必须在包含模式中添加 .

    • 构建您的项目并检查属性文件是否在WEB-INF/classes中可用

    回答你的第二个问题

    classpath:appconfig.properties - 是的 spring 将在WEB-INF/classes 中查找文件

    【讨论】:

    • 我是 - 第一个失败,它正在使用本地计算机 file:// 参考。我使用 Maven 构建项目并将其部署到 Tomcat 7。我检查了生成的战争,它在 \WEB-INF\classes 中有 appconfig.properties
    • 感谢您的编辑,所以即使我使用 classpath:appconfig.properties,它也应该很好,因为属性文件在 war 文件中。所以不知何故我的@Component 类没有初始化?
    【解决方案2】:

    这太傻了……

    当我得到 TestConfig 对象时,我正在做:

    TestConfig config = new TestConfig();
    config.getKey1();
    

    当然,配置对象是一个全新的对象,从未实例化(或注入)任何东西。

    相反,我将其注入,因此它由 Spring 框架初始化:

    @Autowired
    private TestConfig config;
    

    【讨论】:

      猜你喜欢
      • 2016-12-17
      • 2020-02-13
      • 2015-09-29
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      • 2014-09-17
      • 2012-05-27
      • 2018-10-13
      相关资源
      最近更新 更多