java - 在Springboot中,使用@ConfigurationProperties和@PropertySource时如何将属性序列化为对象?

标签 java spring-boot yaml

当将 @ConfigurationProperties 与 @PropertySource(value = "myconfig.yml") 一起使用时,Springboot 不会将我的属性序列化为对象

如果我将相同的配置放入 application.yml 并删除 @PropertySource(value = "myconfig.yml"),那么它就可以工作

---
testPrefix.simpleProperty: my.property.haha
testPrefix.complexProperties:
  -
    firstName: 'Clark'
    lastName: 'Ken'
  -
    firstName: 'Roger'
    lastName: 'Federer'
@Configuration
@ConfigurationProperties(prefix = "testPrefix")
@PropertySource(value = "testConfigFile.yml")
public class MyTestProperties {
  private String simpleProperty;
  private List<Person> complexProperties;

getters

setters
@SpringBootApplication
public class App implements CommandLineRunner {

  MyTestProperties myProperties;

  @Autowired
  public App(MyTestProperties properties) {
    this.properties = properties;
  }

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication((App.class));
    app.run(args);
  }

  @Override
  public void run(String... args) throws Exception {
    System.out.println(myProperties.getSimpleProperty()); 
    myProperties.getComplexProperties.stream.forEach(System.out::println));
  }
}

输出:

my.property.haha

最佳答案

据我所知,YAML 属性无法使用 @PropertySource 加载。我会查一下,因为我不确定问题是否同时得到解决。

[编辑] 显然,它 hasn't已修复:

YAML files cannot be loaded by using the @PropertySource annotation. So, in the case that you need to load values that way, you need to use a properties file.

关于java - 在Springboot中,使用@ConfigurationProperties和@PropertySource时如何将属性序列化为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56367777/

相关文章:

java - Objective-C 相当于 Java 枚举或 "static final"对象

spring - org.springframework.web.client.HttpClientErrorException : 401 Unauthorized

spring - 是否有任何工具或库可以创建用于 Controller 和测试的模拟数据?

postgresql - Azure kubernetes 上的 Postgres 卷权限错误

java - Spring Boot 使用 Yaml 而不是属性文件

azure - 如何从另一个存储库调用二头肌文件?

java - Spring RESTful (Gradle) : @Autowired results in NullPointerException

java - 通过其连接的适配器调用 Activity 的方法对应用程序的面向对象设计有何影响?

java - 在事件上创建方 block

java - Spring Boot SpEL ConditionalOnExpression 检查多个属性