xml转yml时spring.profiles.active必须顶格写为spring.profiles.active: dev,不可嵌套在spring:下;列表用-缩进,map键含点需加引号;@configurationproperties字段名须用kebab-case;2.4+改用spring.config.import且需optional前缀。

XML转YML时spring.profiles.active被忽略
Spring Boot读取YML时,spring.profiles.active必须在顶层(root level),且不能嵌套在spring:下级结构里。XML里常见写法是<property name="spring.profiles.active" value="dev"></property>,直接转成YML的spring: profiles: active: dev会导致配置不生效。
正确写法只有一种:spring.profiles.active: dev,顶格写,前面不能有空格缩进,也不能加spring:前缀块。否则Spring Boot启动时根本不会加载对应profile的配置段。
- 错误示例:
spring:<br> profiles:<br> active: dev
- 正确示例:
spring.profiles.active: dev<br>server.port: 8081
- 如果要多profile,用逗号分隔:
spring.profiles.active: dev,mysql,不是数组或YAML list形式
XML中<list></list>和<map></map>转YML的缩进陷阱
XML里<list></list>常用于@Value注入字符串数组,<map></map>用于@ConfigurationProperties绑定。YML里看似简单,但缩进错一位、冒号后少空格、键名含点号没引号,都会让Spring Boot解析失败甚至静默跳过。
关键原则:YML的层级靠缩进表达,不是靠括号或标签;所有key含.的都建议用引号包裹;列表项前必须是- (短横+空格)。
-
<list><value>redis</value><value>kafka</value></list>→my.services: ["redis", "kafka"]
或更推荐my.services:<br>- redis<br>- kafka
-
<map><entry key="db.url"><value>jdbc:h2:mem:test</value></entry></map>→"my.db":<br> "db.url": "jdbc:h2:mem:test"
(注意db.url加了引号) - 不用
!!list或!!map这类YAML tag——Spring Boot不识别
@ConfigurationProperties绑定时,YML字段名大小写敏感问题
XML里<property name="maxConnectionTimeout" value="3000"></property>转YML写成maxconnectiontimeout: 3000会绑定失败。Spring Boot对@ConfigurationProperties的YML字段名默认按kebab-case(短横线分隔)映射,不是驼峰也不是下划线。
也就是说,Java字段maxConnectionTimeout对应YML必须是max-connection-timeout,不是max_connection_timeout,也不是maxConnectionTimeout。
- Java类字段:
private int maxConnectionTimeout; - 正确YML:
max-connection-timeout: 3000 - 错误YML:
max_connection_timeout: 3000(下划线)、maxConnectionTimeout: 3000(驼峰)、MAX-CONNECTION-TIMEOUT: 3000(大写) - 如需关闭自动转换,加
@ConfigurationProperties(prefix = "my", ignoreInvalidFields = true),但不解决根本问题
Spring Boot 2.4+ 的spring.config.import替代context:property-placeholder
老XML常用<property-placeholder location="classpath:app.properties"></property-placeholder>引入外部属性。Spring Boot 2.4起,这个机制被废弃,改用spring.config.import。直接把XML里的location路径硬搬进YML会报错。
YML里不能写spring.config.import: classpath:app.properties就完事——它只支持optional:classpath:xxx或optional:file:xxx语法,且必须放在application.yml最顶部(不能缩进)。
- 正确写法:
spring:<br> config:<br> import: optional:classpath:app.properties
- 如果app.properties本身含
${}占位符,确保它也在spring.config.import链中被提前加载 - XML中多个
<property-placeholder></property-placeholder>需合并为一个import列表,用逗号分隔:optional:classpath:a.properties,optional:classpath:b.properties
YML不是XML的语法糖,它是Spring Boot配置加载机制的一部分。缩进、命名规则、导入顺序,任何一个点偏移,都会让配置“存在但不起作用”。最麻烦的是没有报错,只是默默用默认值。










