Mastering SpringBoot YAML: Tips, Tricks, and Hidden Pitfalls
This article explores the quirks and advanced features of YAML configuration in SpringBoot, covering string handling, numbers, dictionaries, objects, lists, special data types, and complex key syntax, while providing practical code examples and debugging tips to help Java developers avoid common pitfalls.
I am ashamed to discover that the configuration file world is dominated by yaml, toml, and json, which makes Java developers accustomed to properties files feel embarrassed.
Don't worry, by the end of this article you will also feel a bit ashamed—or perhaps a little angry.
YAML is actually a subset of XML, originating in 2009, and its complexity stems from that heritage. The first hurdle when using yaml files is indentation, similar to Python: nesting is expressed with spaces, not tabs.
For CV enthusiasts, the fact that only the alignment of elements at the same level matters can be a nightmare.
Below are common configuration scenarios demonstrated with SpringBoot's yaml format. A simple test class is used to print the values after they are set.
@EnableAutoConfiguration
@Configuration
public class TestConfig implements InitializingBean {
@Value("${str1}")
String str1;
@Override
public void afterPropertiesSet() throws Exception {
System.out.println(this);
}
}1. Strings
Strings are the simplest and most common configuration. In Spring, strings can be quoted or unquoted, producing the same effect.
str1: ksdfjsdlkfjdsf skdfljs
str1: 'ksdfjsdlkfjdsf skdfljs'
str1: "ksdfjsdlkfjdsf skdfljs"To support multiline text, use the pipe (|) or greater‑than (>) symbols:
str1: |
ksdfjsdlkfjdsf skdfljs
ksdfjsdlkfjdsf skdfljs
ksdfjsdlkfjdsf skdfljs str1: >
ksdfjsdlkfjdsf skdfljs
ksdfjsdlkfjdsf skdfljs
ksdfjsdlkfjdsf skdfljsA third style uses a quoted block:
str1: "ksdfjsdlkfjdsf skdfljs
ksdfjsdlkfjdsf skdfljs
ksdfjsdlkfjdsf skdfljs"2. Numbers
When the target type is numeric, yaml will coerce the value even if it is quoted.
a: "014"The above results in the integer 14. Without quotes:
a: 014YAML interprets a leading zero as octal, so the value becomes 12. Hexadecimal (0x14) becomes 20. Be aware of these conversions.
float: 1.23e+3 # floating‑point
fixed: 13.67 # fixed‑point
minmin: -.inf # negative infinity
notNumber: .NaN # not‑a‑number
boolean: [true, false] # boolean list
string: '12345' # string
date: 2021-06-03 # date3. Dictionaries
Key‑value pairs are separated by a colon. Keys cannot contain special characters unless quoted.
a&& xk@71: 0x14Accessing such a key in Spring:
@Value("${a&& xk@71}")
int a;4. Objects
Objects are just nested dictionaries. Example with a simple Dog class:
@Data
public static class Dog {
private String xjjdog1;
private String xjjdog2;
}
@Bean
@ConfigurationProperties(prefix = "dog")
public Dog getDog() {
return new Dog();
}YAML representation:
dog:
xjjdog1: i am xjjdog1
xjjdog2: i am xjjdog1++Or inline JSON style:
dog: {xjjdog1: 'i am xjjdog1', xjjdog2: 'i am xjjdog++'}Nested prefixes can be flattened:
super.dog: {xjjdog1: 'i am xjjdog1', xjjdog2: 'i am xjjdog++'}5. Lists
Lists can be written in block form or inline:
animal:
- dog
- cat
- monkey animal: [dog, cat, monkey]YAML also supports deep nesting, as shown in a typical Kubernetes pod spec:
apiVersion: v1
kind: Pod
metadata:
name: xjjdog-Pod
labels:
app: front-web
spec:
containers:
- name: front-web
image: nginx
ports:
- containerPort: 80
- name: front-app
image: xjjdog/frontapp
ports:
- containerPort: 14000
storages: ...6. Special Data Types
YAML provides explicit tags to force a type, e.g., !!str to keep a date as a string.
str1: !!str 2021-06-03Other tags include !!int, !!float, !!bool, !!binary, !!timestamp, !!null, !!set, !!omap, !!pairs, !!seq, !!map.
!!int # integer
!!float # floating‑point
!!bool # boolean
!!str # string
!!binary # binary (string)
!!timestamp# date‑time
!!null # null
!!set # set
!!omap, !!pairs # ordered map / pair list
!!seq # sequence (list)
!!map # mapAnchors (&) and aliases (*) allow reuse:
from: &d !!str 2021-06-04
str1: *dKeys themselves can be complex structures:
?[blue, reg, green]: Color7. Conclusion
Armed with these tricks, you can craft sophisticated SpringBoot yaml configurations that are both powerful and hard to tamper with.
Below is an example of a datasource configuration using advanced yaml features:
h2: &sa !!str sa
driver: &driver !!str org.h2.Driver
defaults: &defaults
?username: *sa
?password:
?driverClassName: *driver
spring:
datasource:
<<: *defaults
?url: !!str >
jdbc:h2:mem:h2test;
DB_CLOSE_DELAY=-1;
DB_CLOSE_ON_EXIT=FALSESigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
