Spring Boot Properties
In the world of Spring Boot development, effective application configuration is crucial for building flexible and maintainable applications. Spring Boot's property management system provides a powerful way to configure your applications without modifying code, allowing for environment-specific settings and centralizing configuration.
Introduction to Spring Boot Properties
Spring Boot applications can be configured using properties defined in various sources. These properties control everything from server settings and database connections to custom application behavior. The property system follows a hierarchical approach with clear precedence rules, making it predictable and flexible.
Why Properties Matter
- Externalized Configuration: Keep environment-specific settings separate from code
- No Recompilation: Change application behavior without rebuilding
- Profile Support: Define different configurations for different environments
- Default Values: Provide sensible defaults while allowing overrides
Property Sources and Their Precedence
Spring Boot considers properties from many locations, in the following order (highest to lowest precedence):
- Command-line arguments
- JNDI attributes from
java:comp/env
- Java System properties (
System.getProperties()
) - OS environment variables
- Profile-specific properties (
application-{profile}.properties
) - Application properties (
application.properties
or YAML files) @PropertySource
annotations- Default properties
This means values from higher precedence sources will override the same properties defined in lower precedence sources.
Creating and Using Properties Files
The Standard application.properties
By default, Spring Boot looks for an application.properties
file in the following locations:
- Current directory/config subfolder
- Current directory
- Classpath/config package
- Classpath root
Let's create a simple application.properties
file:
# Server configuration
server.port=8080
server.servlet.context-path=/myapp
# Application information
app.name=My Spring Boot App
app.description=A sample application
app.version=1.0.0
# Custom properties
greeting.message=Hello from application.properties!
Using YAML Configuration
Spring Boot also supports YAML as an alternative to properties files. The same properties as above in YAML format:
server:
port: 8080
servlet:
context-path: /myapp
app:
name: My Spring Boot App
description: A sample application
version: 1.0.0
greeting:
message: Hello from application.yml!
YAML provides a more structured and often more readable format, especially for nested properties.
Accessing Properties in Your Application
Using @Value
Annotation
The simplest way to access properties is using the @Value
annotation:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class GreetingService {
@Value("${greeting.message}")
private String greetingMessage;
@Value("${app.name:Default App Name}")
private String appName; // With default value
public String getGreeting() {
return greetingMessage + " Welcome to " + appName;
}
}
The expression ${property.name}
is used to access a property value. You can also provide default values using a colon, like ${property.name:default value}
.
Using @ConfigurationProperties
For more complex configurations, @ConfigurationProperties
provides a type-safe way to bind properties:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "app")
public class ApplicationProperties {
private String name;
private String description;
private String version;
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
To use this class:
import org.springframework.stereotype.Service;
@Service
public class AppInfoService {
private final ApplicationProperties appProps;
public AppInfoService(ApplicationProperties appProps) {
this.appProps = appProps;
}
public String getApplicationSummary() {
return String.format("%s (v%s): %s",
appProps.getName(),
appProps.getVersion(),
appProps.getDescription());
}
}
Environment-Specific Configuration with Profiles
One of Spring Boot's most powerful features is the ability to define environment-specific properties using profiles.
Creating Profile-Specific Properties
Create files named application-{profile}.properties
or application-{profile}.yml
:
application-dev.properties:
server.port=8080
logging.level.org.springframework=DEBUG
app.environment=Development
application-prod.properties:
server.port=80
logging.level.org.springframework=WARN
app.environment=Production
Activating Profiles
You can activate profiles in several ways:
- Through
application.properties
:
spring.profiles.active=dev
- As a command line argument:
java -jar myapp.jar --spring.profiles.active=prod
- As an environment variable:
export SPRING_PROFILES_ACTIVE=prod
java -jar myapp.jar
- Programmatically:
SpringApplication app = new SpringApplication(MyApplication.class);
app.setAdditionalProfiles("prod");
app.run(args);
Property Encryption and Sensitive Data
For sensitive data like passwords, you can use Spring Cloud Config's encryption capabilities or environment-specific approaches.
A simple approach for development purposes:
- Create an
application.yml
file with placeholders:
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
- Set environment variables before starting your application:
export DB_USERNAME=admin
export DB_PASSWORD=secr3t
java -jar myapp.jar
Practical Examples
Database Configuration
# Database properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JPA/Hibernate properties
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
Logging Configuration
# Log levels
logging.level.root=INFO
logging.level.org.springframework.web=DEBUG
logging.level.com.myapp=DEBUG
# Log file
logging.file.name=application.log
logging.file.path=/var/logs
# Pattern
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n
Custom Application Settings
# Email settings
email.server=smtp.example.com
email.port=587
email.username=notifications@example.com
email.password=emailPassword123
# Feature flags
feature.newui.enabled=true
feature.analytics.enabled=true
Random Value Properties
Spring Boot can generate random values - useful for tests and local development:
# Random values
app.instance-id=${random.uuid}
app.secret=${random.value}
app.number=${random.int}
app.big-number=${random.long}
app.number-in-range=${random.int(100)} # Between 0 and 100
app.number-in-specific-range=${random.int[1024,65535]} # Between 1024 and 65535
Relaxed Binding
Spring Boot uses "relaxed binding" so these property forms are equivalent:
app.page-size
app.pageSize
app.page_size
APP_PAGE_SIZE
This provides flexibility when configuring your application using different conventions.
Summary
Spring Boot's property system provides a flexible foundation for configuring your applications:
- Properties can come from various sources with a clear precedence order
- Configuration can be externalized in properties or YAML files
- Profile-specific properties support different environments
- Type-safe configuration using
@ConfigurationProperties
- Simple value injection using
@Value
By mastering Spring Boot properties, you can create applications that are easy to configure and deploy across different environments without code changes.
Further Reading and Exercises
Additional Resources
- Spring Boot Reference Documentation: Externalized Configuration
- Baeldung: Guide to @ConfigurationProperties in Spring Boot
- Spring Boot YAML Configuration
Exercises
-
Basic Configuration: Create a Spring Boot application with properties for server port, application name, and a custom greeting message.
-
Profile Configuration: Add development, testing, and production profiles with different database settings and logging levels.
-
Type-Safe Configuration: Create a
@ConfigurationProperties
class for email settings with server, port, credentials, and timeouts. -
Command Line Override: Practice overriding properties using command-line arguments.
-
Advanced Exercise: Implement a configuration system that loads properties from an external JSON file in addition to the standard property sources.
If you spot any mistakes on this website, please let me know at feedback@compilenrun.com. I’d greatly appreciate your feedback! :)