【问题标题】:Unable to load properties with Java Spring无法使用 Java Spring 加载属性
【发布时间】: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");
    }
}

【问题讨论】:

  • 我试过了,但还是失败了。

标签: java spring


【解决方案1】:

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

src/main/资源

src/test/resources

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

【讨论】:

  • 感谢您的回复。不幸的是,这行不通,因为我想使用项目资源外部的属性文件。
  • 您是否也尝试过 --spring.config.location=
  • --spring.config.location 是一个命令行参数,仅受 Spring 应用程序支持。如果我尝试 mvn test --spring.config.location,它会说这是一个无效的选项。
【解决方案2】:
@RunWith(SpringRunner.class)
@DataJpaTest
public class AccessPropertiesTest {
    @Value("${my.spring.greeting}")
    String greeting;
    .....
}

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

【讨论】:

  • 感谢您的回复。听起来您描述的配方需要我将配置放在我的项目中的 application.properties 中。但我想使用驻留在项目外部的道具文件。
猜你喜欢
  • 1970-01-01
  • 2015-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-05
  • 2019-03-13
  • 2011-11-27
  • 2016-05-18
相关资源
最近更新 更多