0

我正在尝试将属性文件 (.properties) 加载到我的类中,我在此处的另一个线程中遵循示例:如何从属性文件中读取值?- 但这对我不起作用。

这是我的快速实现:

应用程序上下文.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>

测试配置.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/类的根?

4

2 回答 2

0

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

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

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

回答你的第二个问题

classpath:appconfig.properties- 是的 spring 将在WEB-INF/classes

于 2013-02-23T05:35:41.120 回答
0

这很愚蠢...

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

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

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

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

@Autowired
private TestConfig config;
于 2013-02-24T04:33:55.323 回答