如何在Spring Boot中用yml文件替换属性文件

4

有没有什么特别的要说给Springboot注意作为配置yaml文件而不是属性文件?我正在一个项目中使用Maven和Springboot,如果我把application.properties文件放在资源文件夹中,配置将自动被Springboot识别。

然而,只是用yml文件替换属性文件是不起作用的,文件不再被考虑在内。

是否需要添加一些内容明确告诉SpringBoot使用yml文件?

以下是两个文件:

application.properties:

# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=/WEB-INF/views/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false

以及 application.yml

spring:
  profiles:
    active: ${dario.environment:dev}
  thymeleaf:
    check-template-location: true
    thymeleaf.prefix: /WEB-INF/views/
    thymeleaf.suffix: .html
    thymeleaf.mode: LEGACYHTML5
    spring.thymeleaf.encoding: UTF-8
    spring.thymeleaf.content-type: text/html
    cache: false

嘿,你是怎么在你的yml文件中写出active: ${dario.environment:dev}的?你的yml文件从哪里读取这个呢? - JayC
一个系统属性,即从命令行 -Ddario.environment=prod,如果我没有指定任何属性,则默认采用dev。希望这可以帮助到您。 - fgonzalez
1个回答

3
如果您参考Spring Boot参考文档中的“使用YAML而不是Properties”部分,它会说,只要您的类路径上有SnakeYAML库,Spring Boot就应该自动选择它。
话虽如此,它也指出:
如果您使用“starter POMs”,则可以通过spring-boot-starter自动提供SnakeYAML。

谢谢,我的classpath上已经安装了SnakeYAML,我刚刚找到了问题。我的YML文件格式不正确,我重复了thymeleaf的单词。问题已解决 :) - fgonzalez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接