Week 2 Day 2 — External Configuration, @Value, and @ConfigurationProperties
Goal
Today I want to understand how Spring reads configuration from outside the code.
Main questions:
- What is external configuration?
- Why should configuration not be hardcoded?
- What is
application.properties? - What is
application.yml? - What is the difference between properties and YAML?
- How does Spring Boot load configuration?
- What is
@Value? - What is
@ConfigurationProperties? - When should I use
@Value? - When should I use
@ConfigurationProperties? - How do environment variables override config files?
- What are common exam traps?
1. Quick Review from Week 2 Day 1
In Day 1, I learned:
- Java configuration defines Spring beans with Java code.
@Configurationmarks a class as a source of bean definitions.@Beanmarks a method whose return value becomes a Spring bean.- Full
@Configurationclasses are proxied. @Configuration(proxyBeanMethods = false)disables proxying.- Prefer
@Beanmethod parameters over direct method calls.
Memory sentence:
@Configuration defines bean recipes.
@Bean returns objects that become Spring beans.
Today I learn how to configure values from outside the Java code.
2. What Is External Configuration?
External configuration means:
Values that change between environments should be placed outside Java code.
Examples:
database URL
database username
database password
server port
JWT secret
API base URL
feature flags
email provider
file upload limits
logging level
active profile
Bad:
private String apiUrl = "https://api.production.com";
Better:
external-api:
base-url: https://api.production.com
Then Spring reads this value.
3. Why External Configuration Matters
Hardcoded values are bad because:
- code must be changed for each environment
- secrets may be accidentally committed
- testing becomes harder
- deployment becomes less flexible
- Docker/Kubernetes/cloud deployment becomes harder
- production config should not live inside source code
Good configuration separates:
code = stable logic
configuration = environment-specific values
Memory sentence:
Code should describe behavior. Configuration should describe environment-specific values.
4. Common Environments
Most real applications have several environments.
local
dev
test
staging
prod
docker
ci
Example:
Local database:
jdbc:postgresql://localhost:5432/app
Production database:
jdbc:postgresql://prod-db:5432/app
The code should stay the same.
Only the configuration changes.
5. application.properties
Spring Boot can read configuration from:
application.properties
Example:
server.port=8080
app.name=klarsync
app.max-tasks-per-user=50
external-api.base-url=https://api.example.com
external-api.timeout-seconds=10
This format uses key-value pairs.
6. application.yml
Spring Boot can also read:
application.yml
Example:
server:
port: 8080
app:
name: klarsync
max-tasks-per-user: 50
external-api:
base-url: https://api.example.com
timeout-seconds: 10
YAML is hierarchical.
It is often easier to read for grouped configuration.
7. Properties vs YAML
Both are valid.
Properties
app.name=klarsync
app.max-tasks-per-user=50
app.email.enabled=true
YAML
app:
name: klarsync
max-tasks-per-user: 50
email:
enabled: true
Comparison:
| Topic | .properties | .yml |
|---|---|---|
| Style | flat key-value | hierarchical |
| Readability | good for small config | better for grouped config |
| Indentation sensitive | no | yes |
| Common in Spring Boot | yes | yes |
Important:
Do not use both for the same values unless you clearly understand precedence.
8. Common YAML Mistake
YAML depends on indentation.
Correct:
app:
name: klarsync
email:
enabled: true
Wrong:
app:
name: klarsync
email:
enabled: true
YAML indentation matters.
Exam may not test YAML syntax deeply, but real projects break often because of bad indentation.
9. Where Does Spring Boot Load Configuration From?
Spring Boot can read configuration from many sources.
Common sources:
application.properties
application.yml
profile-specific files
environment variables
command-line arguments
system properties
config data locations
Examples:
application-dev.yml
application-test.yml
application-prod.yml
Command-line example:
java -jar app.jar --server.port=9090
Environment variable example:
SERVER_PORT=9090 java -jar app.jar
10. Important Idea: External Config Can Override File Config
Example file:
server:
port: 8080
Run with:
java -jar app.jar --server.port=9090
Result:
server.port = 9090
The command-line value overrides the file value.
Memory sentence:
Later and higher-priority external configuration can override values from
application.yml.
11. Why This Is Useful in Production
In production, I do not want to rebuild the app just to change a port or database URL.
Example:
SPRING_DATASOURCE_URL=jdbc:postgresql://prod-db:5432/app
SPRING_DATASOURCE_USERNAME=app_user
SPRING_DATASOURCE_PASSWORD=secret
java -jar app.jar
Same application jar.
Different environment config.
12. Environment Variables and Relaxed Binding
Spring Boot supports relaxed binding.
This means different naming styles can map to the same property.
Example property:
external-api.base-url=https://api.example.com
Environment variable:
EXTERNAL_API_BASE_URL=https://api.example.com
These can map to the same configuration value.
Examples that often map together:
external-api.base-url
externalApi.baseUrl
external_api_base_url
EXTERNAL_API_BASE_URL
Memory sentence:
Spring Boot relaxed binding allows different property naming styles to bind to the same configuration field.
13. What Is @Value?
@Value injects a single configuration value.
Example:
app:
name: klarsync
Java:
@Component
public class AppInfo {
@Value("${app.name}")
private String appName;
}
Spring reads:
app.name
and injects it into:
appName
14. @Value with Constructor Injection
Field injection works, but constructor injection is better.
Better:
@Component
public class AppInfo {
private final String appName;
public AppInfo(@Value("${app.name}") String appName) {
this.appName = appName;
}
}
This makes the dependency explicit.
15. @Value Default Value
You can provide a default value.
@Value("${app.name:default-app}")
private String appName;
Meaning:
Use app.name if it exists.
Otherwise use default-app.
Example:
@Value("${external-api.timeout-seconds:5}")
private int timeoutSeconds;
If the property is missing, Spring injects:
5
16. What Happens If @Value Property Is Missing?
Example:
@Value("${app.name}")
private String appName;
If app.name does not exist, Spring usually fails to start.
Typical error:
Could not resolve placeholder 'app.name'
Fixes:
- Add the property.
- Use a default value.
- Use
@ConfigurationProperties. - Make the configuration optional in another way.
17. @Value for Simple Values
@Value is useful for simple one-off values.
Example:
@Component
public class ReportService {
private final int maxReportSize;
public ReportService(
@Value("${report.max-size:100}") int maxReportSize
) {
this.maxReportSize = maxReportSize;
}
}
This is okay because it is only one value.
18. Problem with Too Many @Value Fields
Bad:
@Component
public class ExternalApiClient {
public ExternalApiClient(
@Value("${external-api.base-url}") String baseUrl,
@Value("${external-api.timeout-seconds}") int timeoutSeconds,
@Value("${external-api.retry-count}") int retryCount,
@Value("${external-api.enabled}") boolean enabled
) {
}
}
This works, but it becomes noisy.
Better:
@ConfigurationProperties(prefix = "external-api")
public class ExternalApiProperties {
private String baseUrl;
private int timeoutSeconds;
private int retryCount;
private boolean enabled;
}
Memory sentence:
Use
@Valuefor one value. Use@ConfigurationPropertiesfor grouped values.
19. What Is @ConfigurationProperties?
@ConfigurationProperties binds a group of related properties to a Java object.
Example config:
external-api:
base-url: https://api.example.com
timeout-seconds: 10
retry-count: 3
enabled: true
Java class:
@ConfigurationProperties(prefix = "external-api")
public class ExternalApiProperties {
private String baseUrl;
private int timeoutSeconds;
private int retryCount;
private boolean enabled;
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public int getTimeoutSeconds() {
return timeoutSeconds;
}
public void setTimeoutSeconds(int timeoutSeconds) {
this.timeoutSeconds = timeoutSeconds;
}
public int getRetryCount() {
return retryCount;
}
public void setRetryCount(int retryCount) {
this.retryCount = retryCount;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
Spring binds:
external-api.base-url -> baseUrl
external-api.timeout-seconds -> timeoutSeconds
external-api.retry-count -> retryCount
external-api.enabled -> enabled
20. Registering @ConfigurationProperties
A @ConfigurationProperties class must be registered as a bean.
Common ways:
Option 1 — Add @Component
@Component
@ConfigurationProperties(prefix = "external-api")
public class ExternalApiProperties {
}
Simple and common.
Option 2 — Use @EnableConfigurationProperties
@Configuration
@EnableConfigurationProperties(ExternalApiProperties.class)
public class ExternalApiConfig {
}
Then:
@ConfigurationProperties(prefix = "external-api")
public class ExternalApiProperties {
}
This is clean because the properties class does not need @Component.
Option 3 — Use @ConfigurationPropertiesScan
On main class:
@SpringBootApplication
@ConfigurationPropertiesScan
public class MyApplication {
}
Then Spring scans for @ConfigurationProperties classes.
21. Using @ConfigurationProperties in a Service
Properties class:
@Component
@ConfigurationProperties(prefix = "external-api")
public class ExternalApiProperties {
private String baseUrl;
private int timeoutSeconds;
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public int getTimeoutSeconds() {
return timeoutSeconds;
}
public void setTimeoutSeconds(int timeoutSeconds) {
this.timeoutSeconds = timeoutSeconds;
}
}
Service:
@Service
public class ExternalApiClient {
private final ExternalApiProperties properties;
public ExternalApiClient(ExternalApiProperties properties) {
this.properties = properties;
}
public void callApi() {
System.out.println(properties.getBaseUrl());
}
}
This is cleaner than many @Value annotations.
22. Constructor Binding with Records
Modern Spring Boot works well with immutable configuration properties.
Example YAML:
external-api:
base-url: https://api.example.com
timeout-seconds: 10
retry-count: 3
Java record:
@ConfigurationProperties(prefix = "external-api")
public record ExternalApiProperties(
String baseUrl,
int timeoutSeconds,
int retryCount
) {
}
Register it with:
@SpringBootApplication
@ConfigurationPropertiesScan
public class MyApplication {
}
This is clean and immutable.
23. Why Immutable Configuration Is Nice
Immutable configuration means values cannot change after object creation.
Benefits:
- safer
- easier to reason about
- no setters needed
- better with constructor injection
- less accidental mutation
Example:
public record AppProperties(
String name,
int maxTasks
) {
}
Memory sentence:
Configuration values should usually be read once and treated as immutable.
24. @ConfigurationProperties with Validation
You can validate configuration values.
Example:
@ConfigurationProperties(prefix = "external-api")
@Validated
public class ExternalApiProperties {
@NotBlank
private String baseUrl;
@Min(1)
private int timeoutSeconds;
// getters and setters
}
If config is invalid, the app fails at startup.
This is good.
It means bad production config is detected early.
25. Validation with Record
@ConfigurationProperties(prefix = "external-api")
@Validated
public record ExternalApiProperties(
@NotBlank String baseUrl,
@Min(1) int timeoutSeconds
) {
}
Config:
external-api:
base-url: ""
timeout-seconds: 0
Result:
Application fails to start because configuration is invalid.
This is good for production safety.
26. @Value vs @ConfigurationProperties
| Topic | @Value | @ConfigurationProperties |
|---|---|---|
| Best for | single value | grouped config |
| Type-safe grouping | weak | strong |
| Validation | less clean | very good |
| Metadata support | limited | good |
| Relaxed binding | limited compared to config props | strong |
| Immutability | possible but noisy | clean with records |
| Example | @Value("${app.name}") | AppProperties class |
Memory sentence:
@Valueis for small one-off values.@ConfigurationPropertiesis for structured configuration.
27. Example: Bad vs Good
Bad:
@Service
public class JwtService {
public JwtService(
@Value("${jwt.secret}") String secret,
@Value("${jwt.expiration-minutes}") long expirationMinutes,
@Value("${jwt.issuer}") String issuer
) {
}
}
Good:
@ConfigurationProperties(prefix = "jwt")
public record JwtProperties(
String secret,
long expirationMinutes,
String issuer
) {
}
Service:
@Service
public class JwtService {
private final JwtProperties jwtProperties;
public JwtService(JwtProperties jwtProperties) {
this.jwtProperties = jwtProperties;
}
}
28. Configuration for Your Klarsync-Like App
Example:
app:
name: klarsync
default-language: de
task:
max-open-tasks-per-user: 100
overdue-warning-days: 3
document:
upload:
max-file-size-mb: 20
allowed-types:
- pdf
- png
- jpg
external-api:
tax-office:
base-url: https://api.tax-office.example
timeout-seconds: 10
Properties class:
@ConfigurationProperties(prefix = "app")
public record AppProperties(
String name,
String defaultLanguage,
Task task
) {
public record Task(
int maxOpenTasksPerUser,
int overdueWarningDays
) {
}
}
This groups config cleanly.
29. Lists in @ConfigurationProperties
YAML:
document:
upload:
allowed-types:
- pdf
- png
- jpg
Java:
@ConfigurationProperties(prefix = "document.upload")
public record DocumentUploadProperties(
List<String> allowedTypes
) {
}
Spring binds the YAML list into List<String>.
30. Maps in @ConfigurationProperties
YAML:
app:
roles:
admin: ROLE_ADMIN
employee: ROLE_EMPLOYEE
client: ROLE_CLIENT
Java:
@ConfigurationProperties(prefix = "app")
public record AppProperties(
Map<String, String> roles
) {
}
Spring binds:
admin -> ROLE_ADMIN
employee -> ROLE_EMPLOYEE
client -> ROLE_CLIENT
31. Type Conversion
Spring can convert configuration strings to many types.
Examples:
app:
timeout: 30s
max-file-size: 20MB
start-date: 2026-01-01
Java:
@ConfigurationProperties(prefix = "app")
public record AppProperties(
Duration timeout,
DataSize maxFileSize,
LocalDate startDate
) {
}
Spring Boot can bind these to proper types.
This is powerful and better than using only strings.
32. Common Types for Configuration
Useful types:
String
int / Integer
long / Long
boolean / Boolean
Duration
DataSize
LocalDate
List<T>
Map<K, V>
Enum
nested objects
Example enum:
public enum StorageProvider {
LOCAL,
S3
}
YAML:
storage:
provider: S3
Properties:
@ConfigurationProperties(prefix = "storage")
public record StorageProperties(
StorageProvider provider
) {
}
33. Environment Variables for Nested Config
YAML property:
external-api:
tax-office:
base-url: https://api.example.com
Equivalent environment variable:
EXTERNAL_API_TAX_OFFICE_BASE_URL=https://api.example.com
Spring Boot relaxed binding maps it.
34. Command-Line Arguments
You can override config with command-line arguments.
java -jar app.jar --server.port=9090 --app.name=demo
This sets:
server.port = 9090
app.name = demo
Command-line arguments often have high priority.
35. System Properties
You can also pass Java system properties.
java -Dserver.port=9090 -jar app.jar
This sets:
server.port = 9090
36. Common Spring Boot Properties
Some common built-in properties:
server.port=8080
spring.application.name=klarsync
spring.profiles.active=dev
spring.datasource.url=jdbc:postgresql://localhost:5432/app
spring.datasource.username=postgres
spring.datasource.password=secret
spring.jpa.hibernate.ddl-auto=validate
logging.level.org.springframework.security=DEBUG
management.endpoints.web.exposure.include=health,info,metrics
You do not need to memorize all properties.
But you should know that Spring Boot uses external properties to configure many built-in features.
37. Configuration and Profiles
Profile-specific files:
application-dev.yml
application-test.yml
application-prod.yml
Example:
## application-dev.yml
spring:
datasource:
url: jdbc:postgresql://localhost:5432/app_dev
## application-prod.yml
spring:
datasource:
url: jdbc:postgresql://prod-db:5432/app_prod
Active profile:
java -jar app.jar --spring.profiles.active=prod
We will study profiles more deeply in the next lesson.
38. Do Not Put Secrets in Git
Bad:
jwt:
secret: my-production-secret
Better:
JWT_SECRET=real-secret-from-server
Then bind it to:
jwt:
secret: ${JWT_SECRET}
or let relaxed binding map:
JWT_SECRET=real-secret
to:
jwt.secret
Important production rule:
Do not commit real secrets into Git.
39. Placeholder Syntax
Spring supports placeholders.
app:
name: ${APP_NAME:klarsync}
Meaning:
Use environment variable APP_NAME if it exists.
Otherwise use klarsync.
Example:
external-api:
base-url: ${EXTERNAL_API_BASE_URL:https://api.default.com}
40. Real Question: Which One Should I Use?
Use @Value when:
I need one simple value.
Example:
public ReportService(@Value("${report.max-size:100}") int maxSize) {
}
Use @ConfigurationProperties when:
I have a group of related values.
Example:
jwt:
secret: abc
expiration-minutes: 60
issuer: klarsync
Use:
@ConfigurationProperties(prefix = "jwt")
public record JwtProperties(
String secret,
long expirationMinutes,
String issuer
) {
}
41. Real Question: Is @ConfigurationProperties a Bean Automatically?
Not always.
This class:
@ConfigurationProperties(prefix = "jwt")
public record JwtProperties(String secret) {
}
must still be registered.
Common ways:
@ConfigurationPropertiesScan
or:
@EnableConfigurationProperties(JwtProperties.class)
or:
@Component
@ConfigurationProperties(prefix = "jwt")
Exam trap:
@ConfigurationPropertiesdescribes binding, but the class must also be registered as a bean.
42. Real Question: Can I Use @Value in Static Fields?
Avoid this.
Bad:
@Value("${app.name}")
private static String appName;
Spring injects into bean instances, not normal static state.
Better:
@Component
public class AppInfo {
private final String appName;
public AppInfo(@Value("${app.name}") String appName) {
this.appName = appName;
}
}
Memory sentence:
Spring dependency injection is instance-based, not static-field based.
43. Real Question: Can I Use @Value Inside Any Class?
Only if the class is managed by Spring.
This works:
@Component
public class AppInfo {
public AppInfo(@Value("${app.name}") String appName) {
}
}
This does not work automatically:
public class AppInfo {
@Value("${app.name}")
private String appName;
}
if I create it manually:
AppInfo appInfo = new AppInfo();
Because Spring does not manage that object.
Exam trap:
@Valueworks only on Spring-managed beans.
44. Real Question: What Happens If Type Conversion Fails?
Example:
app:
max-tasks: abc
Java:
@Value("${app.max-tasks}")
private int maxTasks;
Spring cannot convert "abc" to int.
Result:
Application fails to start.
Same with @ConfigurationProperties.
This is good because invalid config is detected early.
45. Real Question: Can @ConfigurationProperties Use Nested Classes?
Yes.
YAML:
app:
task:
max-open: 100
warning-days: 3
Java:
@ConfigurationProperties(prefix = "app")
public record AppProperties(
Task task
) {
public record Task(
int maxOpen,
int warningDays
) {
}
}
This is useful for structured config.
46. Real Question: What Is Relaxed Binding?
Relaxed binding means Spring Boot can bind different property name styles to Java fields.
Example Java field:
private int timeoutSeconds;
Can bind from:
timeout-seconds
timeout_seconds
timeoutSeconds
TIMEOUT_SECONDS
This is especially useful for environment variables.
47. Real Question: @Value and Relaxed Binding
@Value is more direct.
Example:
@Value("${external-api.timeout-seconds}")
private int timeoutSeconds;
The placeholder must match the property key.
@ConfigurationProperties is better for relaxed, structured binding.
Exam memory sentence:
@ConfigurationPropertieshas stronger relaxed binding support than direct@Valueplaceholders.
48. Real Question: How to See Active Config?
Useful ways:
- Check startup logs.
- Use Actuator
/actuator/env. - Use Actuator
/actuator/configprops. - Log selected properties safely.
- Use tests.
Important:
Do not log secrets.
49. Real Question: Why Validate Configuration?
Without validation, the app may start with bad values.
Example:
external-api:
timeout-seconds: 0
This may cause runtime bugs.
With validation:
@ConfigurationProperties(prefix = "external-api")
@Validated
public record ExternalApiProperties(
@Min(1) int timeoutSeconds
) {
}
The app fails at startup.
This is better than failing later in production.
50. Common Exam Traps
Trap 1
@Value is good for one value, not large grouped configuration.
Trap 2
@ConfigurationProperties classes must be registered as beans.
Trap 3
@Value only works in Spring-managed beans.
Trap 4
Environment variables can override values from property files.
Trap 5
Relaxed binding helps map environment variables to property names.
Trap 6
YAML indentation matters.
Trap 7
Missing @Value placeholders can cause startup failure unless a default is provided.
Trap 8
Type conversion errors can cause startup failure.
Trap 9
Do not commit production secrets into Git.
Trap 10
@ConfigurationProperties is better for grouped, type-safe, validated configuration.
51. Interview Answer
Question:
What is external configuration in Spring Boot?
Good answer:
External configuration means storing environment-specific values outside the Java code, usually in application.properties, application.yml, environment variables, command-line arguments, or profile-specific files. This allows the same application code to run in different environments such as local, test, staging, and production. Spring Boot automatically reads these configuration sources and uses them to configure the application.
52. Interview Answer
Question:
What is the difference between
@Valueand@ConfigurationProperties?
Good answer:
@Value is used to inject a single configuration value, for example @Value("${app.name}"). It is simple and useful for one-off values. @ConfigurationProperties is used to bind a group of related properties to a Java object. It is better for structured, type-safe configuration and works well with validation, nested objects, lists, maps, and immutable records.
53. Interview Answer
Question:
When would you use
@ConfigurationProperties?
Good answer:
I would use @ConfigurationProperties when I have several related configuration values, such as JWT settings, external API settings, upload settings, or application feature settings. It keeps configuration organized, type-safe, and easier to validate. It also avoids having many scattered @Value annotations across services.
54. Interview Answer
Question:
How do environment variables work with Spring Boot configuration?
Good answer:
Spring Boot can read configuration from environment variables. Thanks to relaxed binding, an environment variable such as EXTERNAL_API_BASE_URL can bind to a property like external-api.base-url. This is useful in Docker, cloud, and production environments because values can be changed without rebuilding the application.
55. Interview Answer
Question:
Why should secrets not be stored in
application.yml?
Good answer:
Real production secrets should not be committed to Git because they can be leaked. Values such as database passwords, JWT secrets, API keys, and private tokens should come from environment variables, secret managers, or deployment configuration. The application can still reference those values through Spring Boot configuration.
56. Tiny Code Practice
Create this YAML:
jwt:
issuer: klarsync
expiration-minutes: 60
Create this properties record:
@ConfigurationProperties(prefix = "jwt")
public record JwtProperties(
String issuer,
long expirationMinutes
) {
}
Register it:
@SpringBootApplication
@ConfigurationPropertiesScan
public class MyApplication {
}
Inject it:
@Service
public class JwtService {
private final JwtProperties jwtProperties;
public JwtService(JwtProperties jwtProperties) {
this.jwtProperties = jwtProperties;
}
}
Question:
Why is this cleaner than two
@Valueannotations?
Answer:
Because the JWT configuration is grouped into one type-safe object. It is easier to validate, test, and maintain.
57. Tiny Bug Practice
Problem:
@ConfigurationProperties(prefix = "jwt")
public record JwtProperties(
String secret,
long expirationMinutes
) {
}
Service:
@Service
public class JwtService {
public JwtService(JwtProperties jwtProperties) {
}
}
But the application fails:
No qualifying bean of type JwtProperties available
Question:
What is probably missing?
Answer:
The JwtProperties class is not registered as a Spring bean.
Possible fixes:
@ConfigurationPropertiesScan
or:
@EnableConfigurationProperties(JwtProperties.class)
or add:
@Component
@ConfigurationProperties(prefix = "jwt")
Practice Questions and Answers
Question 1
What is external configuration?
Answer:
External configuration means storing environment-specific values outside Java code, for example in application.yml, application.properties, environment variables, command-line arguments, or profile-specific files.
Question 2
Why should configuration not be hardcoded?
Answer:
Configuration should not be hardcoded because values often change between environments. Hardcoding makes deployment less flexible, testing harder, and can expose secrets in source code.
Question 3
What is application.properties?
Answer:
application.properties is a Spring Boot configuration file that stores key-value configuration, such as server.port=8080.
Question 4
What is application.yml?
Answer:
application.yml is a Spring Boot configuration file that stores configuration in YAML format, usually with hierarchical structure.
Question 5
What is the difference between .properties and .yml?
Answer:
.properties uses flat key-value pairs. .yml uses hierarchical indentation-based structure. Both are supported by Spring Boot.
Question 6
What is @Value?
Answer:
@Value injects a single configuration value into a Spring-managed bean.
Question 7
How can I provide a default value with @Value?
Answer:
I can provide a default value like this:
@Value("${app.name:default-app}")
private String appName;
Question 8
What happens if a required @Value property is missing?
Answer:
If a required @Value property is missing and no default is provided, the application usually fails to start with a placeholder resolution error.
Question 9
What is @ConfigurationProperties?
Answer:
@ConfigurationProperties binds a group of related configuration properties to a Java object.
Question 10
When should I use @Value?
Answer:
Use @Value for simple one-off values.
Question 11
When should I use @ConfigurationProperties?
Answer:
Use @ConfigurationProperties for grouped, structured, type-safe, and validated configuration.
Question 12
Does @ConfigurationProperties automatically create a Spring bean?
Answer:
Not always. The @ConfigurationProperties class must also be registered as a Spring bean.
Question 13
How can I register a @ConfigurationProperties class?
Answer:
I can register it with @ConfigurationPropertiesScan, @EnableConfigurationProperties, or by adding @Component to the properties class.
Question 14
What is relaxed binding?
Answer:
Relaxed binding means Spring Boot can bind different naming styles, such as base-url, baseUrl, base_url, and BASE_URL, to the same Java property.
Question 15
How does this environment variable map to a property?
EXTERNAL_API_BASE_URL=https://api.example.com
Answer:
EXTERNAL_API_BASE_URL can map to:
external-api.base-url
through relaxed binding.
Question 16
Can @ConfigurationProperties bind lists and maps?
Answer:
Yes. @ConfigurationProperties can bind lists, maps, nested objects, enums, durations, data sizes, and other types.
Question 17
Why is validation useful for configuration properties?
Answer:
Validation is useful because invalid configuration can be detected at startup instead of causing runtime bugs in production.
Question 18
Can @Value be used in a class created with new?
Answer:
No, not automatically. @Value works only when the object is managed by Spring.
Question 19
Why should secrets not be committed into Git?
Answer:
Secrets should not be committed into Git because they can be leaked. Production secrets should come from environment variables, secret managers, or deployment configuration.
Question 20
What is better for this config: @Value or @ConfigurationProperties?
jwt:
secret: abc
issuer: klarsync
expiration-minutes: 60
Answer:
@ConfigurationProperties is better because jwt.secret, jwt.issuer, and jwt.expiration-minutes are related values and should be grouped into one type-safe configuration object.
Final Memory Sentences
- External configuration keeps environment-specific values outside Java code.
- Spring Boot reads configuration from files, environment variables, command-line arguments, and more.
application.propertiesis flat key-value config.application.ymlis hierarchical config.@Valueinjects one configuration value.@Value("${key:default}")provides a default.- Missing
@Valueplaceholders can fail application startup. @ConfigurationPropertiesbinds grouped config to a Java object.@ConfigurationPropertiesis better for structured and type-safe config.@ConfigurationPropertiesclasses must be registered.@ConfigurationPropertiesScancan scan properties classes.@EnableConfigurationPropertiescan explicitly register properties classes.- Relaxed binding maps different naming styles to Java fields.
- Environment variables can override file configuration.
- Do not commit real secrets into Git.
- Configuration validation catches bad config at startup.
@Valueworks only in Spring-managed beans.