相关疑难解决方法(0)

使用YAML的Spring @PropertySource

Spring Boot允许我们用YAML等价物替换我们的application.properties文件.但是我的测试似乎遇到了麻烦.如果我注释我的TestConfiguration(一个简单的Java配置),它期望一个属性文件.

例如,这不起作用: @PropertySource(value = "classpath:application-test.yml")

如果我在我的YAML文件中有这个:

db:
  url: jdbc:oracle:thin:@pathToMyDb
  username: someUser
  password: fakePassword
Run Code Online (Sandbox Code Playgroud)

我会用这样的东西来利用这些价值观:

@Value("${db.username}") String username
Run Code Online (Sandbox Code Playgroud)

但是,我最终得到了错误:

Could not resolve placeholder 'db.username' in string value "${db.username}"
Run Code Online (Sandbox Code Playgroud)

我如何在测试中利用YAML的优点?

spring spring-boot

89
推荐指数
8
解决办法
9万
查看次数

从 application.yml 读取属性时忽略 Spring 配置文件

我有这个扫描 Spring 上下文的代码:

public void scan() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    context.register(SomeConfig.class);
    context.refresh();
}
Run Code Online (Sandbox Code Playgroud)

我需要从application.yml文件中读取属性,所以在SomeConfig课堂上,我有这个:

@Configuration
@PropertySource(value = "classpath:application.yml", factory = YamlPropertyLoaderFactory.class)
public class SomeConfig {
  //some beans
}
Run Code Online (Sandbox Code Playgroud)

(我从这里复制了 YamlPropertyLoaderFactory 类)

application.yml 是一个典型的 Spring Boot 文件,具有一些按配置文件的属性和一个默认配置文件:

spring:
  profiles:
    active: p1

---

spring:
   profiles: p1

file: file1.txt

---

spring:
   profiles: p2

file: file2.txt
Run Code Online (Sandbox Code Playgroud)

在某些 bean 中,我正在file使用@Value.

当我运行我的应用程序时,我正在传递-Dspring.profiles.active=p1变量,但出现错误:

无法解析值“${file}”中的占位符“文件”

(即使我没有传递任何配置文件,它也应该可以工作,因为 application.yml 的默认配置文件设置为 p1)

如果我从 中删除所有配置文件配置application.yml,它工作正常:

file: …
Run Code Online (Sandbox Code Playgroud)

java spring

6
推荐指数
1
解决办法
3827
查看次数

标签 统计

spring ×2

java ×1

spring-boot ×1