Sub topic 12
Configuring the App with application.properties
This chapter assumes you can run a Spring Boot project, as covered in the earlier chapters, and that you know Java classes, constructors, and annotations. It covers how Spring Boot reads settings, where those settings can come from, and how to get them into your code.
Why configuration lives outside the code
Values such as a port number, a database URL, or a feature flag change between your laptop, a test server, and production. If they are hard-coded, every change means a rebuild. Spring Boot reads them from external sources instead, so one JAR can run in many environments.
The file Initializr creates for this is src/main/resources/application.properties. It is empty at first. Boot loads it at startup and adds its entries to the Spring Environment, the object that holds every setting the application can see.
The properties file format
Each line is a key=value pair. Lines starting with # are comments. Keys are usually dotted names, and the first segment groups related settings.
# Embedded server
server.port=8081
# Application identity
spring.application.name=demo
# Custom settings used later in this chapter
app.greeting=Hello
app.max-items=10Boot defines hundreds of built-in keys, such as server.port and spring.datasource.url. You can also define your own under any prefix, here app. Choose a prefix that cannot collide with Boot's, such as your company or product name.
The YAML alternative
Boot also reads application.yml. YAML expresses the same keys as nested indentation.
server:
port: 8081
spring:
application:
name: demo
app:
greeting: Hello
max-items: 10The two formats are equivalent. YAML avoids repeating prefixes, but it is sensitive to indentation, and tabs are not allowed. If both files exist, the .properties file wins on conflicts. Pick one format per project to avoid confusion.
Reading values in code
There are two common ways to read a setting. @Value injects a single value. @ConfigurationProperties binds a whole group of settings to a typed object.
Single values with @Value
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private final String greeting;
public GreetingController(@Value("${app.greeting:Hi}") String greeting) {
this.greeting = greeting;
}
@GetMapping("/greet")
public String greet() {
return greeting + " from Spring Boot";
}
}The placeholder ${app.greeting:Hi} reads app.greeting. The text after the colon is a default, used when the key is missing. Without a default, a missing key stops the application at startup with an IllegalArgumentException about an unresolvable placeholder. That is a useful failure, because it surfaces the problem at startup instead of at the first request.
Grouped values with @ConfigurationProperties
When several settings belong together, a typed class is easier to maintain than many @Value fields. A Java record works well because it is immutable.
package com.example.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "app")
public record AppProperties(String greeting, int maxItems) {
}Boot must be told to find this class. The simplest way is @ConfigurationPropertiesScan on the main class.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
@SpringBootApplication
@ConfigurationPropertiesScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}You can then inject AppProperties into any bean through its constructor. Binding converts app.max-items=10 into the int component maxItems. If the value were ten, startup would fail with a binding error that names the property.
| Aspect | `@Value` | `@ConfigurationProperties` |
|---|---|---|
| Best for | One or two values | A group of related values |
| Type conversion | Yes | Yes, including lists and nested objects |
| Relaxed key names | Limited | Full |
| Metadata for IDE hints | No | Yes, with the configuration processor |
Relaxed binding
Boot matches names loosely. In a file, the recommended style is lowercase kebab case, such as app.max-items. That key binds to a maxItems component. The same setting can also be written as app.maxItems, app.max_items, or the environment variable APP_MAXITEMS. This matters because environment variables cannot contain dots or hyphens. Use uppercase with underscores there: SERVER_PORT sets server.port.
Where settings can come from
The properties file is only one source. Boot merges many, and when two define the same key, the one higher in the order wins. The list below is simplified, from highest to lowest priority.
This order lets you keep safe defaults in the file and override them without editing it. The commands below change the port for a single run of the packaged JAR.
# Command-line argument (highest priority of these three)
java -jar target/demo-0.0.1-SNAPSHOT.jar --server.port=9090
# Java system property
java -Dserver.port=9090 -jar target/demo-0.0.1-SNAPSHOT.jar
# Environment variable
SERVER_PORT=9090 java -jar target/demo-0.0.1-SNAPSHOT.jarBoot also reads an application.properties placed next to the JAR, in the working directory or in a config subdirectory. That file overrides the one packed inside the JAR. This lets operations staff change settings without rebuilding.
Profiles: settings per environment
A profile is a named set of settings for one environment. Boot loads application-{profile}.properties on top of the base file when that profile is active.
# application-dev.properties
server.port=8082
app.greeting=Hello from devActivate it with a property, an argument, or an environment variable.
./mvnw spring-boot:run -Dspring-boot.run.profiles=dev
java -jar target/demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
SPRING_PROFILES_ACTIVE=prod java -jar target/demo-0.0.1-SNAPSHOT.jarOnly keys that differ need to appear in the profile file. Everything else falls back to application.properties. Boot logs the active profile at startup, for example The following 1 profile is active: "dev", which is the quickest way to confirm what was loaded.
Placeholders and secrets
A value can refer to another key or to an environment variable, with an optional default.
app.greeting=Hello
app.banner=${app.greeting}, welcome to ${spring.application.name}
spring.datasource.password=${DB_PASSWORD}Do not commit real passwords or API keys to application.properties. Supply them through environment variables or a secrets manager, and reference them with placeholders as shown above.
Common errors
- A typo does nothing. Boot ignores unknown keys in the file. If
server.prot=8081has no effect, check the spelling. The startup log lineTomcat started on port 8080shows what was applied. - The file is not in the right place. It must be at the root of the classpath, so
src/main/resources. A file insrc/main/javais not copied into the build output. - The port is already in use. Startup fails with
Port 8080 was already in use. Changeserver.port, or set it to0to let the operating system choose a free port. - YAML indentation mistakes. A wrong indent moves a key under the wrong parent, and it silently stops working. Use two spaces and no tabs.
- An unexpected value wins. An environment variable or a leftover command-line argument may override the file. Check the order above.
- Whitespace in values. Trailing spaces on a properties line are kept as part of the value in some cases. Trim the lines.
- A profile file is never loaded. The name must be exactly
application-<profile>.properties, and the profile must be active.
Verifying your changes
- Set
app.greeting=Helloandserver.port=8081inapplication.properties. - Run
./mvnw spring-boot:runand look forTomcat started on port 8081. - Call
curl http://localhost:8081/greetand expectHello from Spring Boot. - Stop the app, run it again with
--app.greeting=Howdy, and call the endpoint to see the override take effect.
Exercise
The file contains server.port=8081, and you start the JAR with SERVER_PORT=9090 java -jar app.jar --server.port=7070. Which port does the server use, and why?
Show answer
Port 7070. A command-line argument has higher priority than an environment variable, and both outrank application.properties.
Exercise
You add app.max-items=ten and bind it to int maxItems in an @ConfigurationProperties record. What happens at startup, and how does this differ from a typo in the key name such as app.max-itmes=10?
Show answer
The value ten cannot convert to an int, so binding fails and the application stops with an error naming the property. A misspelled key is not an error, because Boot ignores unknown keys. The record component then gets its default value, which is 0 for an int, so the typo goes unnoticed unless you check the value.