06 - Spring Boot Notes
A beginner-to-advanced guide to Spring Boot core concepts for Spring Professional Certification candidates. Covers auto-configuration,
@SpringBootApplication, starter dependencies, profiles, externalized configuration, Actuator, configuration properties, interview questions, and a quick cheat sheet.
Table of Contents
- What Is Spring Boot?
- Auto Configuration
@SpringBootApplication- Starter Dependencies
- Profiles
- Externalized Configuration
- Actuator
- Configuration Properties
- Common Spring Boot Flow
- Common Mistakes
- Certification Traps
- Interview Questions
- Summary Tables
- One-Page Cheat Sheet
1. What Is Spring Boot?
Spring Boot is an opinionated extension of the Spring Framework that makes it faster to create production-ready Spring applications.
Spring Boot helps with:
| Problem | Spring Boot Solution |
|---|---|
| Too much manual configuration | Auto-configuration |
| Complex dependency setup | Starter dependencies |
| Manual server deployment | Embedded servlet containers |
| Environment-specific setup | Profiles and externalized configuration |
| Production monitoring | Actuator |
| Repetitive property binding | Configuration properties |
Spring Boot does not replace Spring. It builds on top of Spring and reduces boilerplate.
Plain Spring vs Spring Boot
| Plain Spring | Spring Boot |
|---|---|
| Manual bean and infrastructure configuration | Auto-configures common infrastructure |
| Dependencies chosen one by one | Starters group compatible dependencies |
| External server often required for web apps | Embedded Tomcat, Jetty, or Undertow |
| Production endpoints must be added manually | Actuator provides ready-made endpoints |
2. Auto Configuration
Auto-configuration is the Spring Boot feature that automatically configures Spring beans based on:
- Classes available on the classpath
- Existing beans in the
ApplicationContext - Configuration properties
- The current web application type
- Conditional annotations
Example:
If spring-boot-starter-web is on the classpath, Spring Boot detects Spring MVC and an embedded servlet container, then auto-configures a web application.
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
With the web starter, Boot can automatically configure:
| Component | Auto-configured By Boot |
|---|---|
DispatcherServlet | Yes |
| Embedded Tomcat | Yes |
| JSON conversion with Jackson | Yes |
| Spring MVC infrastructure | Yes |
| Error handling | Yes |
How Auto Configuration Works
At startup:
Application starts
|
v
@SpringBootApplication enables auto-configuration
|
v
Spring Boot loads auto-configuration classes
|
v
Conditional annotations decide what applies
|
v
Matching infrastructure beans are registered
Conditional Annotations
Auto-configuration classes rely heavily on conditions.
| Annotation | Meaning |
|---|---|
@ConditionalOnClass | Apply only if a class exists on the classpath |
@ConditionalOnMissingClass | Apply only if a class is missing |
@ConditionalOnBean | Apply only if a bean exists |
@ConditionalOnMissingBean | Apply only if a bean does not already exist |
@ConditionalOnProperty | Apply only if a property has a specific value |
@ConditionalOnWebApplication | Apply only for a web application |
@ConditionalOnNotWebApplication | Apply only for a non-web application |
Example:
@Configuration
@ConditionalOnClass(DataSource.class)
class DataSourceAutoConfiguration {
}
This configuration is considered only when DataSource is available.
@ConditionalOnMissingBean
This is one of the most important Boot conditions.
It lets Boot provide a default bean only when the user has not defined one.
@Bean
@ConditionalOnMissingBean
ObjectMapper objectMapper() {
return new ObjectMapper();
}
If the application already defines an ObjectMapper, Boot backs off.
Overriding Auto Configuration
You usually override Boot defaults by defining your own bean.
@Configuration
class JacksonConfig {
@Bean
ObjectMapper objectMapper() {
return new ObjectMapper().findAndRegisterModules();
}
}
Boot sees the custom bean and avoids creating its default one when the auto-configuration uses @ConditionalOnMissingBean.
Excluding Auto Configuration
Auto-configuration can be excluded when needed.
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class DemoApplication {
}
Or with properties:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
Exclusion should be used carefully. Prefer configuring or overriding beans before excluding an auto-configuration class.
Debugging Auto Configuration
Enable Boot's condition evaluation report:
debug=true
Or run with:
java -jar app.jar --debug
This shows which auto-configurations matched and which did not.
3. @SpringBootApplication
@SpringBootApplication is the main annotation used on a Spring Boot application class.
It combines three annotations:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {
}
Included Annotations
| Annotation | Purpose |
|---|---|
@SpringBootConfiguration | Marks the class as a Spring configuration class |
@EnableAutoConfiguration | Enables Spring Boot auto-configuration |
@ComponentScan | Scans components from the package of the main class downward |
Typical Usage
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
Component Scanning Rule
Spring scans from the package containing the main application class and all child packages.
Recommended structure:
com.example.orders
OrderApplication.java
controller
OrderController.java
service
OrderService.java
repository
OrderRepository.java
If OrderApplication is in com.example.orders, all subpackages are scanned.
Common Component Scan Problem
Problem:
com.example.app
AppApplication.java
com.example.shared
SharedService.java
SharedService is outside the default scan path.
Possible fixes:
@SpringBootApplication(scanBasePackages = "com.example")
public class AppApplication {
}
Or move the main class to a common root package.
SpringApplication.run
SpringApplication.run:
- Creates an
ApplicationContext - Prepares the environment
- Loads beans
- Applies auto-configuration
- Starts the embedded server for web applications
- Publishes application events
ConfigurableApplicationContext context =
SpringApplication.run(OrderApplication.class, args);
4. Starter Dependencies
Starter dependencies are curated dependency descriptors that group related libraries for a specific use case.
They reduce dependency management work.
Example Maven dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
This starter includes dependencies for:
- Spring MVC
- Embedded Tomcat
- Jackson JSON support
- Validation and web infrastructure dependencies
Common Starters
| Starter | Purpose |
|---|---|
spring-boot-starter | Core starter, logging, auto-configuration support |
spring-boot-starter-web | Spring MVC REST/web apps with embedded Tomcat |
spring-boot-starter-webflux | Reactive web apps with Spring WebFlux |
spring-boot-starter-data-jpa | Spring Data JPA, Hibernate, transaction support |
spring-boot-starter-jdbc | JDBC and connection pool support |
spring-boot-starter-security | Spring Security |
spring-boot-starter-test | Testing with JUnit, Mockito, AssertJ, Spring Test |
spring-boot-starter-actuator | Production monitoring endpoints |
spring-boot-starter-validation | Jakarta Bean Validation |
spring-boot-starter-amqp | RabbitMQ messaging |
Starter Naming
Official starters use:
spring-boot-starter-*
Third-party starters should normally use:
*-spring-boot-starter
Dependency Management
Spring Boot manages dependency versions through its parent POM or BOM.
Using the Boot parent:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.0</version>
<relativePath/>
</parent>
Using the Boot BOM:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>3.3.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Usually you should not specify versions for dependencies managed by Spring Boot.
5. Profiles
Profiles let you register different beans and use different configuration values for different environments.
Common profile names:
| Profile | Typical Use |
|---|---|
dev | Local development |
test | Automated tests |
qa | QA environment |
prod | Production |
Activating Profiles
In application.properties:
spring.profiles.active=dev
In application.yml:
spring:
profiles:
active: dev
From command line:
java -jar app.jar --spring.profiles.active=prod
From environment variable:
SPRING_PROFILES_ACTIVE=prod
Profile-Specific Files
Spring Boot automatically loads profile-specific files:
application.properties
application-dev.properties
application-prod.properties
Or:
application.yml
application-dev.yml
application-prod.yml
When the dev profile is active, Boot loads both:
application.propertiesapplication-dev.properties
Profile-specific values override common values.
Profile-Specific Beans
@Service
@Profile("dev")
class DevEmailService implements EmailService {
}
@Service
@Profile("prod")
class SmtpEmailService implements EmailService {
}
Only beans matching the active profile are registered.
Profile Expressions
@Profile("dev | test")
class LocalEmailService {
}
@Profile("!prod")
class NonProductionConfig {
}
Default Profile
If no profile is active, Spring uses the default profile.
@Profile("default")
@Bean
DataSource localDataSource() {
return dataSource;
}
6. Externalized Configuration
Externalized configuration means configuration values are kept outside compiled code, so the same application can run in different environments.
Examples:
server.port=8081
spring.datasource.url=jdbc:postgresql://localhost:5432/orders
app.currency=INR
Why It Matters
| Hardcoded Value | Externalized Value |
|---|---|
| Requires code change | Change property only |
| Same value everywhere | Environment-specific values |
| Risky for secrets | Can use environment variables or secret stores |
| Hard to test | Easy to override in tests |
Common Configuration Sources
Spring Boot can read configuration from many places, including:
- Default properties
application.propertiesapplication.yml- Profile-specific files
- Environment variables
- Java system properties
- Command-line arguments
- Test property sources
Common Property File Locations
Boot commonly loads:
classpath:/application.properties
classpath:/application.yml
file:./application.properties
file:./application.yml
file:./config/application.properties
file:./config/application.yml
External files can override packaged files.
Property Precedence
When the same property appears in multiple places, the source with higher precedence wins.
Common high-precedence sources include:
| Source | Example |
|---|---|
| Command-line arguments | --server.port=9090 |
| Java system properties | -Dserver.port=9090 |
| Environment variables | SERVER_PORT=9090 |
| Profile-specific files | application-prod.properties |
| Common config files | application.properties |
Command-line arguments usually override values from property files.
Using @Value
@Service
class PricingService {
private final String currency;
PricingService(@Value("${app.currency}") String currency) {
this.currency = currency;
}
}
Use @Value for simple, isolated values.
Default Values With @Value
@Value("${app.timeout-seconds:30}")
private int timeoutSeconds;
If app.timeout-seconds is missing, the value is 30.
YAML Example
server:
port: 8081
app:
currency: INR
timeout-seconds: 30
Equivalent properties:
server.port=8081
app.currency=INR
app.timeout-seconds=30
Environment Variable Binding
Environment variables commonly use uppercase and underscores:
SERVER_PORT=9090
APP_TIMEOUT_SECONDS=60
These can bind to:
server.port
app.timeout-seconds
Spring Boot uses relaxed binding for property names.
7. Actuator
Spring Boot Actuator provides production-ready features for monitoring and managing applications.
Add the starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Common Actuator Endpoints
| Endpoint | Purpose |
|---|---|
/actuator/health | Application health information |
/actuator/info | Application information |
/actuator/metrics | Metrics names and metric data |
/actuator/env | Environment properties |
/actuator/beans | Beans in the application context |
/actuator/mappings | Request mappings |
/actuator/configprops | Configuration properties |
/actuator/loggers | View and change logger levels |
/actuator/threaddump | Thread dump |
/actuator/heapdump | Heap dump |
Endpoint Exposure
By default, only limited web endpoints are exposed.
Expose selected endpoints:
management.endpoints.web.exposure.include=health,info,metrics
Expose all endpoints:
management.endpoints.web.exposure.include=*
Do not expose sensitive endpoints publicly in production.
Health Endpoint
GET /actuator/health
Typical response:
{
"status": "UP"
}
Show health details:
management.endpoint.health.show-details=when_authorized
Common health indicators:
| Indicator | Checks |
|---|---|
db | Database connectivity |
diskSpace | Available disk space |
ping | Basic application responsiveness |
redis | Redis connectivity |
rabbit | RabbitMQ connectivity |
Info Endpoint
management.info.env.enabled=true
info.app.name=Order Service
info.app.version=1.0.0
GET /actuator/info
Metrics Endpoint
GET /actuator/metrics
GET /actuator/metrics/jvm.memory.used
GET /actuator/metrics/http.server.requests
Spring Boot Actuator integrates with Micrometer for metrics.
Management Port and Base Path
Change Actuator base path:
management.endpoints.web.base-path=/manage
Change management port:
management.server.port=9090
Then health is available at:
http://localhost:9090/manage/health
Securing Actuator
If Spring Security is present, Actuator endpoints should be protected.
Example:
@Configuration
class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/health", "/actuator/info").permitAll()
.requestMatchers("/actuator/**").hasRole("ADMIN")
.anyRequest().authenticated())
.build();
}
}
8. Configuration Properties
@ConfigurationProperties binds external configuration to type-safe Java objects.
It is preferred over many scattered @Value annotations when values are related.
Basic Example
Properties:
app.payment.provider=stripe
app.payment.timeout=30s
app.payment.retry-count=3
Java:
@ConfigurationProperties(prefix = "app.payment")
public class PaymentProperties {
private String provider;
private Duration timeout;
private int retryCount;
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
public Duration getTimeout() {
return timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public int getRetryCount() {
return retryCount;
}
public void setRetryCount(int retryCount) {
this.retryCount = retryCount;
}
}
Enable scanning:
@SpringBootApplication
@ConfigurationPropertiesScan
public class PaymentApplication {
}
Use it:
@Service
class PaymentClient {
private final PaymentProperties properties;
PaymentClient(PaymentProperties properties) {
this.properties = properties;
}
}
Constructor Binding
In Spring Boot 3, constructor binding works naturally for single-constructor configuration properties classes.
@ConfigurationProperties(prefix = "app.payment")
public record PaymentProperties(
String provider,
Duration timeout,
int retryCount
) {
}
Validation
Add validation constraints:
@Validated
@ConfigurationProperties(prefix = "app.payment")
public record PaymentProperties(
@NotBlank String provider,
@NotNull Duration timeout,
@Min(0) int retryCount
) {
}
If invalid configuration is supplied, application startup fails.
Enabling Configuration Properties
There are three common ways:
| Approach | Example |
|---|---|
| Scan properties classes | @ConfigurationPropertiesScan |
| Enable a specific class | @EnableConfigurationProperties(PaymentProperties.class) |
| Define as a bean | @Bean method annotated with @ConfigurationProperties |
@ConfigurationProperties vs @Value
| Feature | @ConfigurationProperties | @Value |
|---|---|---|
| Best for | Groups of related properties | Single simple value |
| Type safety | Strong | Limited |
| Validation | Good support | Manual |
| Relaxed binding | Yes | Less suitable |
| Metadata support | Yes | No |
| Maintainability | Better for larger configs | Fine for small cases |
Relaxed Binding
These property names can bind to the same Java property retryCount:
app.payment.retry-count=3
app.payment.retryCount=3
app.payment.retry_count=3
APP_PAYMENT_RETRY_COUNT=3
9. Common Spring Boot Flow
main method
|
v
SpringApplication.run
|
v
Environment prepared
|
v
ApplicationContext created
|
v
Components scanned
|
v
Auto-configuration applied
|
v
Beans created and dependencies injected
|
v
Embedded server starts, if web application
|
v
Application is ready
Minimal REST Application
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RestController
class HelloController {
@GetMapping("/hello")
String hello() {
return "Hello Spring Boot";
}
}
With spring-boot-starter-web, this is enough to start a REST application.
10. Common Mistakes
| Mistake | Why It Is a Problem | Better Approach |
|---|---|---|
| Placing main class in a narrow package | Components outside child packages are not scanned | Put main class in root package |
| Adding versions for every dependency | Can conflict with Boot dependency management | Let Boot manage versions |
| Exposing all Actuator endpoints in production | Can leak sensitive data | Expose only needed endpoints and secure them |
Using many @Value fields | Hard to validate and maintain | Use @ConfigurationProperties |
| Hardcoding environment values | Requires code changes per environment | Use externalized configuration |
| Using one profile for too many concerns | Configuration becomes confusing | Keep profiles environment-focused |
| Excluding auto-configuration too early | May disable useful infrastructure | Override beans or set properties first |
11. Certification Traps
@SpringBootApplicationincludes@ComponentScan,@EnableAutoConfiguration, and@SpringBootConfiguration.- Auto-configuration is conditional and backs off when user-defined beans exist.
- Starters are dependency descriptors, not code generators.
- Spring Boot does not replace the Spring Framework.
- Profiles control bean registration and profile-specific configuration.
- Externalized configuration allows the same artifact to run in multiple environments.
- Command-line arguments can override property files.
@ConfigurationPropertiesis type-safe and supports validation.- Actuator endpoints are not all exposed over HTTP by default.
- Exposing
/actuator/env,/actuator/beans,/actuator/configprops, or heap dumps can be sensitive. - Spring Boot applications can be non-web applications.
- Embedded Tomcat is included by
spring-boot-starter-web, not by every Boot application.
12. Interview Questions
1. What is Spring Boot?
Spring Boot is an opinionated framework built on top of Spring that simplifies application setup using auto-configuration, starter dependencies, embedded servers, externalized configuration, and production-ready Actuator features.
2. What is auto-configuration?
Auto-configuration automatically configures Spring beans based on the classpath, existing beans, properties, and conditions. It reduces manual setup for common application features.
3. How does Spring Boot decide which auto-configuration to apply?
It uses conditional annotations such as @ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty, and @ConditionalOnWebApplication.
4. How can you override auto-configuration?
Usually by defining your own bean. Many Boot auto-configurations use @ConditionalOnMissingBean, so Boot backs off when the application provides a custom bean.
5. How can you exclude an auto-configuration class?
Use the exclude attribute of @SpringBootApplication or the spring.autoconfigure.exclude property.
6. What does @SpringBootApplication include?
It includes @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan.
7. What is the purpose of SpringApplication.run?
It bootstraps the application by preparing the environment, creating the application context, loading beans, applying auto-configuration, and starting the embedded server if needed.
8. What are starter dependencies?
Starters are curated dependency sets for specific features, such as web, JPA, security, testing, and Actuator. They simplify dependency management.
9. What is spring-boot-starter-web?
It is a starter for building Spring MVC web and REST applications. It commonly includes Spring MVC, Jackson, validation support, and embedded Tomcat.
10. Why should dependency versions usually be omitted in a Boot application?
Spring Boot manages compatible versions through its parent POM or dependency management BOM. Manually overriding versions can create compatibility problems.
11. What are Spring profiles?
Profiles allow different beans and configuration values to be used in different environments, such as dev, test, and prod.
12. How do you activate a profile?
Use spring.profiles.active, a command-line argument, a Java system property, or the SPRING_PROFILES_ACTIVE environment variable.
13. What is externalized configuration?
Externalized configuration stores environment-specific values outside the compiled code, usually in property files, YAML files, environment variables, or command-line arguments.
14. What is the difference between @Value and @ConfigurationProperties?
@Value is useful for simple individual values. @ConfigurationProperties is better for groups of related properties because it is type-safe, maintainable, and supports validation.
15. What is Spring Boot Actuator?
Actuator provides production-ready endpoints for health checks, metrics, environment inspection, logging, mappings, and application monitoring.
16. Which Actuator endpoint checks application health?
/actuator/health.
17. Are all Actuator endpoints exposed by default?
No. Only limited endpoints are exposed over HTTP by default. Additional endpoints must be explicitly exposed.
18. How do you expose Actuator metrics over HTTP?
management.endpoints.web.exposure.include=health,info,metrics
19. What is relaxed binding?
Relaxed binding allows different property name formats, such as retry-count, retryCount, retry_count, and RETRY_COUNT, to bind to the same Java property.
20. What happens if validated configuration properties are invalid?
Application startup fails with a binding or validation error.
13. Summary Tables
Core Spring Boot Features
| Feature | Purpose |
|---|---|
| Auto-configuration | Configures infrastructure automatically |
| Starters | Group dependencies by use case |
| Embedded server | Runs web apps as executable jars |
| Profiles | Switch environment-specific beans and properties |
| Externalized configuration | Keeps config outside code |
| Actuator | Adds production monitoring and management |
| Configuration properties | Type-safe property binding |
Important Annotations
| Annotation | Purpose |
|---|---|
@SpringBootApplication | Main Boot application annotation |
@SpringBootConfiguration | Specialized configuration annotation |
@EnableAutoConfiguration | Enables auto-configuration |
@ComponentScan | Scans components |
@Profile | Registers beans only for matching profiles |
@ConfigurationProperties | Binds properties to Java objects |
@ConfigurationPropertiesScan | Scans for configuration properties classes |
@EnableConfigurationProperties | Enables specific configuration properties classes |
@ConditionalOnClass | Conditional on classpath |
@ConditionalOnMissingBean | Conditional on missing bean |
@ConditionalOnProperty | Conditional on property value |
Important Properties
| Property | Purpose |
|---|---|
server.port | Changes application HTTP port |
spring.application.name | Sets application name |
spring.profiles.active | Activates profiles |
spring.autoconfigure.exclude | Excludes auto-configuration classes |
management.endpoints.web.exposure.include | Exposes Actuator endpoints |
management.endpoint.health.show-details | Controls health detail visibility |
management.server.port | Runs Actuator on a different port |
management.endpoints.web.base-path | Changes Actuator base path |
Configuration Mechanisms
| Mechanism | Best Use |
|---|---|
application.properties | Simple key-value configuration |
application.yml | Hierarchical configuration |
| Profile-specific files | Environment-specific overrides |
| Environment variables | Deployment-specific values |
| Command-line arguments | Runtime overrides |
@Value | Single values |
@ConfigurationProperties | Groups of related values |
14. One-Page Cheat Sheet
Spring Boot Purpose
Spring Boot simplifies Spring application development with:
Auto-configuration + Starters + Embedded server + External config + Actuator
Main Class
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
@SpringBootApplication Equals
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
Auto Configuration
Classpath + Beans + Properties + Conditions = Auto-configured beans
Important conditions:
@ConditionalOnClass
@ConditionalOnMissingBean
@ConditionalOnProperty
@ConditionalOnWebApplication
Starters
spring-boot-starter-web -> MVC REST app
spring-boot-starter-data-jpa -> JPA and Hibernate
spring-boot-starter-security -> Security
spring-boot-starter-actuator -> Monitoring
spring-boot-starter-test -> Testing
Profiles
spring.profiles.active=dev
@Profile("prod")
@Service
class SmtpEmailService implements EmailService {
}
Externalized Configuration
server.port=8081
spring.application.name=order-service
Command-line override:
java -jar app.jar --server.port=9090
Configuration Properties
@ConfigurationProperties(prefix = "app")
public record AppProperties(String name, Duration timeout) {
}
Enable scanning:
@ConfigurationPropertiesScan
@SpringBootApplication
class App {
}
Actuator
Dependency:
spring-boot-starter-actuator
Common endpoints:
/actuator/health
/actuator/info
/actuator/metrics
/actuator/env
/actuator/beans
/actuator/configprops
Expose endpoints:
management.endpoints.web.exposure.include=health,info,metrics
Must Remember
| Topic | Key Point |
|---|---|
| Boot | Built on Spring, does not replace Spring |
| Auto-configuration | Conditional and can back off |
| Starters | Dependency bundles |
| Profiles | Environment-specific beans and config |
| External config | Same app artifact, different environments |
| Actuator | Production monitoring endpoints |
| Config properties | Type-safe property binding |