Spring读取属性文件,但值为null

时间:2015-07-18 13:40:52

标签: java spring properties-file spring-properties

我真的不明白这里的问题。我正在尝试在Spring应用程序中使用属性文件。该文件似乎被读取,但如果我尝试读取值,我会得到null。

这是我的上下文(部分)xml:

RecyclerView

我在src / main / resources

下有我的test.properties

当我尝试像这样运行时:

<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:aws-context="http://www.springframework.org/schema/cloud/aws/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/tx 
http://www.springframework.org/schema/tx/spring-tx-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/cloud/aws/context
http://www.springframework.org/schema/cloud/spring-cloud-aws-context.xsd">

<tx:annotation-driven />

<context:component-scan base-package="my.package" />

<context:annotation-config />

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

<!-- OTHER STUFF HERE -->
</beans>

输出将是:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:META-INF/spring/context-test.xml")
public class SimpleTest {

    @Autowired
    private ApplicationContext context;

    @Autowired
    private Environment environment;

    @Test
    public void test() throws Exception {
        System.out.println(environment);
        System.out.println(environment.getProperty("my.test"));
    }
}

所以我假设我应该在“propertySources”中看到除了系统属性之外的东西吗?

此外,如果我将xml行更改为:

StandardEnvironment {activeProfiles=[], defaultProfiles=[default], propertySources=[systemProperties,systemEnvironment]}
null

我收到FileNotFound异常,这意味着文件本身已加载?那么为什么我不能加载它的属性呢?

在test.properties中我只有这个:

<context:property-placeholder location="classpath:test.properties2" />

这可能是什么问题?

1 个答案:

答案 0 :(得分:1)

Property-placeholder不会自动向环境公开属性。你应该像这样注入你的财产:

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