java - Spring读取属性文件但值为空

标签 java spring properties-file spring-properties

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

这是我的上下文 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

这可能是什么问题?

最佳答案

Property-placeholder 不会自动向环境公开属性。您应该像这样注入(inject)您的属性(property):

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

关于java - Spring读取属性文件但值为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31491753/

相关文章:

java - Firebase 推送 - 身份验证凭据无效

Java从多次存在的config.properties文件中获取某个属性

java - 需要在java文件夹中获取日志文件

java - 如何为 Spring Boot 创建内部属性文件?

java - 在 Spring 中访问 webapp 文件夹中的文件/目录

java - 如何输入将分配给变量的字符串?

java - 如何在 Java 中将类显示为 JSON 响应?

java - 如何将 spring aop 与来自外部 jar 的类一起使用

java - 如何为 JTable 标题设置自定义工具提示位置?

java - IDE 支持 Spring 框架;它们值得使用吗?