【发布时间】:2020-07-16 13:41:12
【问题描述】:
我是 Spring 的新手。我试图弄清楚如何从通过 Spring 注入我的应用程序的 props 文件中访问属性。
我写了一个下面提供的简单测试。我通过 JRE 选项提供的环境变量传递属性文件的位置来运行它
$ mvn test -DSPRING_CONFIG_NAME=my_spring \
-DSPRING_CONFIG_LOCATION=file:///Users/desilets/Documents/conf
这里是 my_spring.properties 文件的内容
$ cat /Users/desilets/Documents/conf/my_spring.properties
my.spring.greeting=hello world
当我运行测试时,它失败了。然而输出表明环境变量很受欢迎:
SPRING_CONFIG_NAME=my_spring
SPRING_CONFIG_LOCATION=file:///Users/desilets/Documents/conf
greeting=null
我做错了什么?
谢谢。
---- 测试代码 ---
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
public class AccessPropertiesTest {
@Value("${my.spring.greeting}")
String greeting;
@Test
public void test__LoadProperties() throws Exception {
System.out.println("SPRING_CONFIG_NAME="+
System.getProperty("SPRING_CONFIG_NAME"));
System.out.println("SPRING_CONFIG_LOCATION="+
System.getProperty("SPRING_CONFIG_LOCATION"));
System.out.println("greeting="+greeting);
Assert.assertEquals(
"The property my.spring.greeting was not read correctly",
greeting, "hello world");
}
}
【问题讨论】:
-
我试过了,但还是失败了。