MindIQ Academy

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

  1. What Is Spring Boot?
  2. Auto Configuration
  3. @SpringBootApplication
  4. Starter Dependencies
  5. Profiles
  6. Externalized Configuration
  7. Actuator
  8. Configuration Properties
  9. Common Spring Boot Flow
  10. Common Mistakes
  11. Certification Traps
  12. Interview Questions
  13. Summary Tables
  14. 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:

ProblemSpring Boot Solution
Too much manual configurationAuto-configuration
Complex dependency setupStarter dependencies
Manual server deploymentEmbedded servlet containers
Environment-specific setupProfiles and externalized configuration
Production monitoringActuator
Repetitive property bindingConfiguration properties

Spring Boot does not replace Spring. It builds on top of Spring and reduces boilerplate.

Plain Spring vs Spring Boot

Plain SpringSpring Boot
Manual bean and infrastructure configurationAuto-configures common infrastructure
Dependencies chosen one by oneStarters group compatible dependencies
External server often required for web appsEmbedded Tomcat, Jetty, or Undertow
Production endpoints must be added manuallyActuator provides ready-made endpoints

2. Auto Configuration

Auto-configuration is the Spring Boot feature that automatically configures Spring beans based on:

  1. Classes available on the classpath
  2. Existing beans in the ApplicationContext
  3. Configuration properties
  4. The current web application type
  5. 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:

ComponentAuto-configured By Boot
DispatcherServletYes
Embedded TomcatYes
JSON conversion with JacksonYes
Spring MVC infrastructureYes
Error handlingYes

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.

AnnotationMeaning
@ConditionalOnClassApply only if a class exists on the classpath
@ConditionalOnMissingClassApply only if a class is missing
@ConditionalOnBeanApply only if a bean exists
@ConditionalOnMissingBeanApply only if a bean does not already exist
@ConditionalOnPropertyApply only if a property has a specific value
@ConditionalOnWebApplicationApply only for a web application
@ConditionalOnNotWebApplicationApply 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

AnnotationPurpose
@SpringBootConfigurationMarks the class as a Spring configuration class
@EnableAutoConfigurationEnables Spring Boot auto-configuration
@ComponentScanScans 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:

  1. Creates an ApplicationContext
  2. Prepares the environment
  3. Loads beans
  4. Applies auto-configuration
  5. Starts the embedded server for web applications
  6. 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:

  1. Spring MVC
  2. Embedded Tomcat
  3. Jackson JSON support
  4. Validation and web infrastructure dependencies

Common Starters

StarterPurpose
spring-boot-starterCore starter, logging, auto-configuration support
spring-boot-starter-webSpring MVC REST/web apps with embedded Tomcat
spring-boot-starter-webfluxReactive web apps with Spring WebFlux
spring-boot-starter-data-jpaSpring Data JPA, Hibernate, transaction support
spring-boot-starter-jdbcJDBC and connection pool support
spring-boot-starter-securitySpring Security
spring-boot-starter-testTesting with JUnit, Mockito, AssertJ, Spring Test
spring-boot-starter-actuatorProduction monitoring endpoints
spring-boot-starter-validationJakarta Bean Validation
spring-boot-starter-amqpRabbitMQ 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:

ProfileTypical Use
devLocal development
testAutomated tests
qaQA environment
prodProduction

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:

  1. application.properties
  2. application-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 ValueExternalized Value
Requires code changeChange property only
Same value everywhereEnvironment-specific values
Risky for secretsCan use environment variables or secret stores
Hard to testEasy to override in tests

Common Configuration Sources

Spring Boot can read configuration from many places, including:

  1. Default properties
  2. application.properties
  3. application.yml
  4. Profile-specific files
  5. Environment variables
  6. Java system properties
  7. Command-line arguments
  8. 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:

SourceExample
Command-line arguments--server.port=9090
Java system properties-Dserver.port=9090
Environment variablesSERVER_PORT=9090
Profile-specific filesapplication-prod.properties
Common config filesapplication.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

EndpointPurpose
/actuator/healthApplication health information
/actuator/infoApplication information
/actuator/metricsMetrics names and metric data
/actuator/envEnvironment properties
/actuator/beansBeans in the application context
/actuator/mappingsRequest mappings
/actuator/configpropsConfiguration properties
/actuator/loggersView and change logger levels
/actuator/threaddumpThread dump
/actuator/heapdumpHeap 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:

IndicatorChecks
dbDatabase connectivity
diskSpaceAvailable disk space
pingBasic application responsiveness
redisRedis connectivity
rabbitRabbitMQ 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:

ApproachExample
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 forGroups of related propertiesSingle simple value
Type safetyStrongLimited
ValidationGood supportManual
Relaxed bindingYesLess suitable
Metadata supportYesNo
MaintainabilityBetter for larger configsFine 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

MistakeWhy It Is a ProblemBetter Approach
Placing main class in a narrow packageComponents outside child packages are not scannedPut main class in root package
Adding versions for every dependencyCan conflict with Boot dependency managementLet Boot manage versions
Exposing all Actuator endpoints in productionCan leak sensitive dataExpose only needed endpoints and secure them
Using many @Value fieldsHard to validate and maintainUse @ConfigurationProperties
Hardcoding environment valuesRequires code changes per environmentUse externalized configuration
Using one profile for too many concernsConfiguration becomes confusingKeep profiles environment-focused
Excluding auto-configuration too earlyMay disable useful infrastructureOverride beans or set properties first

11. Certification Traps

  1. @SpringBootApplication includes @ComponentScan, @EnableAutoConfiguration, and @SpringBootConfiguration.
  2. Auto-configuration is conditional and backs off when user-defined beans exist.
  3. Starters are dependency descriptors, not code generators.
  4. Spring Boot does not replace the Spring Framework.
  5. Profiles control bean registration and profile-specific configuration.
  6. Externalized configuration allows the same artifact to run in multiple environments.
  7. Command-line arguments can override property files.
  8. @ConfigurationProperties is type-safe and supports validation.
  9. Actuator endpoints are not all exposed over HTTP by default.
  10. Exposing /actuator/env, /actuator/beans, /actuator/configprops, or heap dumps can be sensitive.
  11. Spring Boot applications can be non-web applications.
  12. 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

FeaturePurpose
Auto-configurationConfigures infrastructure automatically
StartersGroup dependencies by use case
Embedded serverRuns web apps as executable jars
ProfilesSwitch environment-specific beans and properties
Externalized configurationKeeps config outside code
ActuatorAdds production monitoring and management
Configuration propertiesType-safe property binding

Important Annotations

AnnotationPurpose
@SpringBootApplicationMain Boot application annotation
@SpringBootConfigurationSpecialized configuration annotation
@EnableAutoConfigurationEnables auto-configuration
@ComponentScanScans components
@ProfileRegisters beans only for matching profiles
@ConfigurationPropertiesBinds properties to Java objects
@ConfigurationPropertiesScanScans for configuration properties classes
@EnableConfigurationPropertiesEnables specific configuration properties classes
@ConditionalOnClassConditional on classpath
@ConditionalOnMissingBeanConditional on missing bean
@ConditionalOnPropertyConditional on property value

Important Properties

PropertyPurpose
server.portChanges application HTTP port
spring.application.nameSets application name
spring.profiles.activeActivates profiles
spring.autoconfigure.excludeExcludes auto-configuration classes
management.endpoints.web.exposure.includeExposes Actuator endpoints
management.endpoint.health.show-detailsControls health detail visibility
management.server.portRuns Actuator on a different port
management.endpoints.web.base-pathChanges Actuator base path

Configuration Mechanisms

MechanismBest Use
application.propertiesSimple key-value configuration
application.ymlHierarchical configuration
Profile-specific filesEnvironment-specific overrides
Environment variablesDeployment-specific values
Command-line argumentsRuntime overrides
@ValueSingle values
@ConfigurationPropertiesGroups 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

TopicKey Point
BootBuilt on Spring, does not replace Spring
Auto-configurationConditional and can back off
StartersDependency bundles
ProfilesEnvironment-specific beans and config
External configSame app artifact, different environments
ActuatorProduction monitoring endpoints
Config propertiesType-safe property binding