Application Configuration

Basic Spring
≈ 2 min read

Settings live outside Java code

A server port, an external service address, a pool size, or a feature flag should not be hard-coded into a class. Spring Boot can read configuration from external sources and provide it to the application at startup. The most familiar option is an application.properties or application.yml file.

server.port=8081
app.message=Hello

The same settings can come from environment variables, command-line arguments, and other supported sources. This allows the same built artifact to run with different parameters without recompilation.

Reading a single value

For a small number of independent settings, a value can be injected directly into a bean:

@Component
class GreetingService {
    private final String message;

    GreetingService(@Value("${app.message}") String message) {
        this.message = message;
    }
}

Spring resolves the ${app.message} expression from the current environment and passes the value through the constructor. When there are many related properties, it is more convenient to avoid dozens of @Value annotations and group them into a separate typed object. That is the next topic.

Configuration and secrets are not the same thing. Passwords, tokens, and keys should not be stored in the repository together with a regular application.properties file. It is better to provide them through a protected external environment.