无法使用Java Spring加载属性



我是Spring的新手。我正试图弄清楚如何从通过Spring注入我的应用程序的道具文件中访问属性。

我在下面写了一个简单的测试。我通过在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

我做错了什么?

Thx。

----测试代码---

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

如果是春季项目,属性将有两个位置

src/main/resources

src/test/resources

如果您运行测试,它将从src/test/resources中进行选择。

@RunWith(SpringRunner.class)
@DataJpaTest
public class AccessPropertiesTest {
@Value("${my.spring.greeting}")
String greeting;
.....
}

参考https://www.baeldung.com/spring-boot-testing
add:my.spring.greeting=anyValue到application.properties或application.properties.yaml文件