2.5 Environment Variables and Configuration Properties (application.yml, @ConfigurationProperties)
Spring Boot provides various ways to easily separate external configurations from the application code. In this chapter, we will look into how to utilize application.yml and @ConfigurationProperties which provides type safety.
1. application.properties vs application.yml
Although Spring Boot generates an application.properties file by default, the YAML format is overwhelmingly preferred in practice because it allows for hierarchical configuration.
application.yml Example:
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: password
2. Injecting Single Values using @Value
The simplest way to inject property values is using the @Value annotation.
@Service
public class EmailService {
@Value("${spring.mail.host}")
private String mailHost;
public void sendEmail() {
System.out.println("Host: " + mailHost);
}
}
While @Value is simple, typos or missing values can cause runtime errors and it lacks type safety.
3. Type-Safe Mapping using @ConfigurationProperties
In production, it is highly recommended to logically group configuration values into a single Java Bean object using @ConfigurationProperties.
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "app.aws.s3")
public class AwsS3Properties {
private String accessKey;
private String secretKey;
private String bucketName;
}
To activate these properties, add @ConfigurationPropertiesScan to the main class, or simply attach @Component to the class itself.
# application.yml
app:
aws:
s3:
access-key: AKIA...
secret-key: aBcd...
bucket-name: my-asset-bucket
Advantages of @ConfigurationProperties
- Robust IDE auto-completion support preventing simple typos.
- Detects type mismatch errors before runtime at application startup.
- Can be validated continuously by combining with
JSR-303(@Validated).