【问题标题】:Spring reads property file but values are nullSpring读取属性文件但值为空
【发布时间】:2015-07-18 13:40:51
【问题描述】:

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

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

<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>

我的 test.properties 在 src/main/resources 下

当我尝试像这样运行它时:

@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"));
    }
}

输出将是:

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

所以我认为除了系统属性之外,我应该在“propertySources”中看到一些东西,对吧?

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

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

我得到一个 FileNotFound 异常,这意味着文件本身已加载?那么为什么我不能从中加载属性呢?

在 test.properties 我只有这个:

my.test=123456

这可能是什么问题?

【问题讨论】:

    标签: java spring properties-file spring-properties


    【解决方案1】:

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

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

    【讨论】:

    • 根据 Spring 文档,我可以通过 Environment 对象作为 context.getEnvironment() 访问所有这些。此外,您的解决方案很有趣,但我更喜欢另一种方式。
    • 好吧,我猜另一种方式更复杂,我只是想访问在我的环境中未定义但它们在生产中定义的环境变量。但是,是的,我想您的解决方案可能会奏效。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2023-02-03
    • 2013-05-26
    • 2020-07-01
    • 2015-12-23
    • 2018-05-24
    • 2016-04-29
    相关资源
    最近更新 更多