Springboot 无法读取 Yaml 配置

Springboot Unable to Read Yaml config

我正在尝试一些关于 YAML 配置的事情,好像我遗漏了什么。

下面是我的控制器class和Yaml文件。

HomeController.java

@Controller
@PropertySource("file:${user.dir}/config/webappdemo.yml")
public class HomeController {
    
    @Value("${app.message}")
    private String appMessage;

    @GetMapping("/home")
    @ResponseBody
    public String homePage() {
        return this.appMessage;
    }
}

webappdemo.yml

app:
   message: hello

我的应用程序无法启动,但出现以下异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'app.message' in value "${app.message}"
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:405) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1413) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean[=12=](AbstractBeanFactory.java:335) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.9.jar:5.3.9]

从错误消息中我能感觉到,由于某种原因,无法找到 属性 如果我修改 属性 文件如下,它的工作,请帮助我确定问题:

webappdemo.yml

app.message=hello

PropertySource 不支持 .yml,在这种情况下您需要使用 .properties 文件。

“无法使用@PropertySource 或@TestPropertySource 注释加载 YAML 文件。因此,如果您需要以这种方式加载值,则需要使用属性文件”

来自官方文档https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#boot-features-external-config-yaml-shortcomings

您可能会在 Spring @PropertySource using YAML

中找到 solutions/workarounds