Sub topic 2
Writing application.properties and application.yaml
This chapter covers the two main configuration file formats in Spring Boot. It assumes you can read YAML and .properties syntax, have a Spring Boot project built with Maven or Gradle, and know what a Spring bean is. Binding to classes, profiles and precedence get their own chapters. Here the focus is the files themselves: where they live, how they are written, and the mistakes people make with them.
Where Boot looks for the files
Spring Boot loads application.properties and application.yaml automatically at startup. It checks these locations, from lowest to highest priority:
- The classpath root, for example
src/main/resources/application.yaml. - A
/configpackage on the classpath. - The current working directory, next to the jar.
- A
config/subdirectory of the current working directory. - Immediate subdirectories of
config/in the working directory.
Files found later in this list override files found earlier. Values do not replace whole files. Boot merges them key by key, so a file next to the jar can change one property and leave the rest to the packaged file.
Both formats can exist in the same project. If both define the same key in the same location, .properties wins over .yaml. Boot also accepts the older .yml extension.
The same settings in both formats
Both formats describe a tree of keys. A .properties file flattens the tree with dots. YAML expresses it with indentation.
app.mail.host=localhost
app.mail.port=1025
[email protected]
app.mail.retry-attempts=3app:
mail:
host: localhost
port: 1025
sender: [email protected]
retry-attempts: 3Both files produce the same four properties: app.mail.host, app.mail.port, app.mail.sender and app.mail.retry-attempts. Code never sees which format a value came from.
| Aspect | `.properties` | `.yaml` |
|---|---|---|
| Structure | Flat keys joined by dots | Nested by indentation |
| Repeated prefixes | Repeated on every line | Written once |
| Lists | `key[0]=a`, `key[1]=b` or `key=a,b` | `- a` entries under the key |
| Comments | `#` or `!` | `#` |
| Multiple documents | Not supported in one file the same way | Separated by `---` |
| Indentation errors | Not applicable | Possible and easy to make |
Neither format is better in general. YAML reads well for deeply nested settings and lists of objects. .properties is harder to break with whitespace and is simple to generate or patch with tools. Pick one per project and keep to it, because mixing them makes it hard to see where a value comes from.
Lists and maps
Lists need care because the two formats write them differently.
app:
allowed-origins:
- https://example.com
- https://admin.example.com
limits:
upload-mb: 10
requests-per-minute: 120app.allowed-origins[0]=https://example.com
app.allowed-origins[1]=https://admin.example.com
app.limits.upload-mb=10
app.limits.requests-per-minute=120A comma-separated value also works for simple lists when the target type is a list or array:
app.allowed-origins=https://example.com,https://admin.example.comDo not mix indexed and comma-separated forms for the same key across files. A list defined in a higher-priority file replaces the whole list from a lower-priority file. It does not merge by index. If the packaged file has three entries and an override file has one, the result has one entry.
Multi-document YAML
A single YAML file can hold several documents separated by a line containing ---. Each document can be tied to a condition. This is the reason many projects prefer YAML for environment-specific settings.
app:
mail:
host: localhost
port: 1025
sender: [email protected]
retry-attempts: 3
---
spring:
config:
activate:
on-profile: prod
app:
mail:
host: smtp.example.com
port: 587The first document has no condition, so it always applies. The second applies only when the prod profile is active. Boot reads documents in order, and later documents override earlier ones. When prod is active, host becomes smtp.example.com and port becomes 587. sender and retry-attempts keep the values from the first document.
Properties files can do something similar with a line of #--- between sections. Put spring.config.activate.on-profile=prod in the section that should be conditional. Profiles themselves are covered in a later chapter. For now, treat on-profile as a switch.
Value types and quoting
A property value is always text when it is read. Conversion to numbers, booleans, durations and so on happens later, when the value is injected or bound. This explains several common surprises.
- In YAML, an unquoted
yes,no,onoroffmay be parsed as a boolean by some parsers. Quote values that must stay strings. - A leading zero, such as
007, can be read as an octal number in YAML. Quote it if it is an identifier. - In YAML, a value containing
:or starting with*,&,{or[needs quotes. - In
.properties, surrounding spaces after the=are trimmed. Quotes are not special and become part of the value.
app:
region-code: "007"
feature-flag: "on"
greeting: "Hello: welcome"A .properties file written with quotes keeps them:
app.greeting="Hello"That value is the string "Hello" including the quote characters. This is a frequent source of stray quotes in output.
Placeholders and default values
A property value can refer to another property with ${...}. Boot resolves the reference when the property is read. A default can follow a colon.
app:
name: demo
mail:
sender: "noreply@${app.domain:example.com}"
subject-prefix: "[${app.name}] "If app.domain is not defined, the sender is [email protected]. If app.name is not defined and no default is given, startup fails with a placeholder resolution error. That failure is useful. A missing value is easier to find at startup than later at runtime.
To write a literal ${, escape it in the value or avoid the sequence. This matters for values such as password hashes or template strings.
Common errors
Most problems with config files come from a small set of causes.
- File not found.
application.yamlplaced insrc/test/javaor the project root is not on the classpath. Place it insrc/main/resources. - Key ignored. A typo such as
app.mial.hostproduces no error by default. The key is simply never read. Binding with validation, covered later, catches many of these. - Wrong indentation. In YAML, two keys at the wrong depth become different properties. Use spaces only, never tabs.
- Duplicate keys. A repeated key in the same YAML document can fail to parse or silently keep the last value, depending on the parser version. Do not repeat keys.
- Stale build output. Boot reads the copy in
target/classesorbuild/resources. If an IDE does not rebuild resources, an edit seems to have no effect. - Unexpected override. A file in the working directory or a
config/folder shadows the packaged file. Check the working directory when a value differs from the file you edited.
A small runnable check
You can confirm that a file is loaded with a short application that prints one property. This example assumes the application.yaml shown earlier is in src/main/resources.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
CommandLineRunner printHost(@Value("${app.mail.host}") String host) {
return args -> System.out.println("Mail host: " + host);
}
}With no profile active, this prints Mail host: localhost. Start it with --spring.profiles.active=prod and it prints Mail host: smtp.example.com. The @Value annotation is explained in a later chapter. It is used here only to read a value.
Exercise
Your packaged application.yaml defines app.allowed-origins with three list entries. A file at ./config/application.yaml next to the jar defines the same key with one entry. How many entries does the application see, and why? Also, how would the result differ for a scalar key such as app.mail.port that only the packaged file defines?
Show answer
The application sees one entry. A list from a higher-priority location replaces the whole list and is not merged by index. The scalar app.mail.port still comes from the packaged file, because Boot merges files key by key and only the keys defined in the override file are replaced.
Exercise
A teammate writes app.greeting="Hello" in application.properties and sees quotes in the log output. What is happening, and what is the fix?
Show answer
In .properties files, quotes are not special, so they become part of the value. The fix is to write app.greeting=Hello. In YAML, quotes are syntax and are removed when the value is parsed.