Spring Boot and Spring Framework internals feature image showing layered architecture, core modules, and HTTP request processing flow.

Spring Boot and Spring Framework Internals — Architecture, Modules, and Request Processing Explained

Spring is one of the most widely used ecosystems for building enterprise Java applications, yet many developers use Spring Boot daily without fully understanding how Spring actually works under the hood.

Spring Framework is a foundational Java framework that provides inversion of control (IoC), dependency injection (DI), transaction management, and infrastructure support for enterprise systems.
Spring Boot is an extension of Spring Framework that simplifies configuration and deployment through auto-configuration, embedded servers, and production-ready defaults.

Although often discussed together, Spring Framework and Spring Boot solve different problems. Spring provides the core runtime and programming model, while Spring Boot standardizes how Spring is configured and executed in modern applications.

This article explains the internal architecture of Spring Boot and Spring Framework, including:

  • how the Spring container manages beans
  • how ApplicationContext and BeanFactory differ
  • how HTTP requests are routed through DispatcherServlet
  • how major Spring modules (MVC, ORM, AOP, Security, Messaging, and Concurrency) fit together in real systems

Rather than focusing on annotations or quick-start examples, this article takes a concept-first, system-level approach. The goal is to provide a clear mental model of how Spring Boot applications are structured and how requests, dependencies, and lifecycle management work in production environments.

Who This Article Is For

This article is written for Java developers, backend engineers, and system designers who want to understand Spring Boot and Spring Framework beyond surface-level usage, and who care about correctness, performance, scalability, and long-term maintainability.

By the end of this article, you should be able to reason confidently about Spring internals, debug complex behavior, and design Spring-based systems with intent rather than convention alone.

In short: Spring Framework provides the core container and programming model, while Spring Boot simplifies configuration and runtime behavior without changing how Spring works internally.

1. Why Spring Exists (The Real Problem It Solves)

Before Spring, Java enterprise applications commonly suffered from:

  • Tight coupling between components
  • Hard-to-test code due to widespread new object creation
  • XML-heavy configuration (EJB era)
  • Business logic polluted with infrastructure concerns

Spring solved these problems using Inversion of Control (IoC).

Instead of your code controlling object creation, the framework controls it.

Objects do not create their dependencies — the container does.

This single principle enabled:

  • Clean, layered architecture
  • Loose coupling
  • Testability
  • Replaceable implementations
  • Cross-cutting concerns (transactions, security, logging)

Everything in Spring builds on this foundation.

2. Spring Framework vs Spring Boot (A Clear Mental Model)

Spring Framework

Spring Framework is the core engine that provides:

  • Dependency Injection
  • Bean lifecycle management
  • Aspect-Oriented Programming (AOP)
  • Transaction management
  • Resource abstraction

Spring Boot

Spring Boot adds:

  • Auto-configuration
  • Embedded servers
  • Starter dependencies
  • Production-ready defaults

Think of it this way:

Spring Framework = engine
Spring Boot = fully assembled car

Spring Boot still uses the same Spring container internally.

Key Comparison

AspectSpring FrameworkSpring Boot
RoleCore engineAutomation layer
ConfigurationExplicitConvention-based
ServerExternalEmbedded
TargetFlexibilitySpeed and consistency

Spring Boot uses Spring Framework internally — it does not hide it.

3. Spring Module Ecosystem (High-Level View)

Spring applications are composed of layered modules:

  • Core Container (IoC, DI)
  • Application Modules (MVC, ORM, AOP, Security, Messaging)
  • Boot Layer (auto-configuration, starters)
  • Infrastructure (Servlet container, JVM, databases, queues)

Spring Ecosystem Overview (Custom Diagram)

Spring Boot and Spring Framework internal architecture diagram illustrating layered design from Java Servlet JVM to Spring Core container, application modules, and Spring Boot auto-configuration, starters, actuator, and profiles.

Spring Boot automates configuration, but all modules run on the same Spring container.

4. Core Container — ApplicationContext and BeanFactory

BeanFactory (Low-Level Container)

BeanFactory is the minimal IoC container.

Responsibilities:

  • Create beans
  • Inject dependencies
  • Manage scope

Characteristics:

  • Lazy initialization
  • Lightweight
  • Minimal features

You rarely use it directly in modern Spring applications.

ApplicationContext (Enterprise Container)

ApplicationContext extends BeanFactory and adds:

  • Event publishing
  • AOP support
  • Transaction management
  • Resource loading
  • Internationalization
  • Web integration

Comparison

FeatureBeanFactoryApplicationContext
Dependency injectionYesYes
Bean lifecycleBasicFull
EventsNoYes
AOPNoYes
TransactionsNoYes
Web supportNoYes

Rule of thumb:

Frameworks use BeanFactory. Applications use ApplicationContext.

At runtime, the ApplicationContext is the brain of Spring.

Constructor Injection (Preferred)

@Service
public class OrderService {

    private final PaymentService paymentService;

    public OrderService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }
}

Why constructor injection:

  • Dependencies are explicit
  • Immutable design
  • Easier unit testing
  • Fails fast if misconfigured

5. Dependency Injection in Spring — Types of Injection (and When to Use Each)

Dependency Injection (DI) is the mechanism Spring uses to assemble your application graph: it creates objects (beans), resolves their dependencies, and wires them together based on configuration metadata (annotations, Java config, or XML). In practice, Spring supports three common injection styles: constructor injection, setter injection, and field injection.

1) Constructor Injection (Recommended Default)

Constructor injection supplies all required dependencies through a class constructor. This is the most robust option because it makes dependencies explicit, enables immutability, and prevents partially constructed objects.

Why Spring teams prefer it

  • Dependencies are mandatory and obvious
  • Enables final fields (immutability)
  • Easier to unit test (no container required)
  • Prevents runtime “null injection” surprises

Example

@Service
public class OrderService {

    private final PaymentGateway paymentGateway;
    private final OrderRepository orderRepository;

    public OrderService(PaymentGateway paymentGateway, OrderRepository orderRepository) {
        this.paymentGateway = paymentGateway;
        this.orderRepository = orderRepository;
    }

    // business methods...
}

When to use

  • Almost always for core services
  • When dependencies are required for correct operation

2) Setter Injection (Good for Optional Dependencies)

Setter injection supplies dependencies after object construction via setter methods. This works well when a dependency is optional or when you want to support reconfiguration in limited cases.

Tradeoffs

  • The object can exist temporarily in a partially configured state
  • You must be careful with null-handling or defaults

Example

@Service
public class ReportService {

    private Formatter formatter = new DefaultFormatter(); // fallback

    @Autowired(required = false)
    public void setFormatter(Formatter formatter) {
        this.formatter = formatter;
    }

    // business methods...
}

When to use

  • Optional components (formatters, plugins, feature toggles)
  • Legacy designs where constructor signatures are already complex

3) Field Injection (Works, but Usually Avoid)

Field injection injects dependencies directly into class fields (typically using @Autowired). It is the most concise, but it hides dependencies and relies on reflection-based injection.

Why it’s discouraged in production-grade code

  • Dependencies are not visible via the constructor API
  • Harder to test without Spring
  • Encourages mutable design and makes refactoring riskier

Example

@Service
public class InventoryService {

    @Autowired
    private InventoryRepository inventoryRepository;

    // business methods...
}

When it can be acceptable

  • Small prototypes or quick demos
  • Extremely simple components where testability is not a concern

For long-lived systems, prefer constructor injection.

How Spring Resolves “Which Bean to Inject”

When multiple beans match the same type, Spring needs a selection rule. Common resolution strategies:

@Primary (Choose a default implementation)

@Primary
@Component
public class StripePaymentGateway implements PaymentGateway { }

@Qualifier (Choose a specific bean by name/qualifier)

@Service
public class CheckoutService {

    private final PaymentGateway paymentGateway;

    public CheckoutService(@Qualifier("paypalPaymentGateway") PaymentGateway paymentGateway) {
        this.paymentGateway = paymentGateway;
    }
}

By parameter name (when names match and qualifiers are present)

Spring can use parameter names and bean names as a fallback in some cases, but @Qualifier is the most explicit and safest option.

DI Best Practice Summary (Internals-friendly)

  • Prefer constructor injection for required dependencies.
  • Use setter injection only for optional dependencies (and define defaults if needed).
  • Avoid field injection for production-grade code because it reduces testability and hides dependencies.
  • Use @Qualifier when more than one implementation exists, and @Primary when one should be the default.

6. Spring Bean Lifecycle (How Spring Manages Objects)

In Spring, a bean is any object managed by the Spring container. While many developers treat beans as “just services,” the type and scope of a bean directly influence application behavior, memory usage, concurrency safety, and performance.

Understanding bean scopes is essential when designing scalable, production-grade Spring applications.

Bean Types in Spring (By Responsibility)

Spring does not enforce strict semantic differences between component types at runtime, but annotations communicate intent, improve readability, and help tooling and teams reason about architecture.

AnnotationPurposeTypical Layer
@ComponentGeneric Spring-managed beanShared utilities
@ServiceBusiness logic, domain servicesService layer
@RepositoryData access + exception translationPersistence layer
@ControllerMVC controller returning viewsWeb layer
@RestControllerREST API controllerWeb / API layer
@ConfigurationBean definitions via Java configInfrastructure

Why These Distinctions Matter

  • @Repository enables automatic exception translation
  • @Service expresses business intent
  • @RestController combines @Controller + @ResponseBody
  • Clear separation improves AI indexing, code navigation, and maintainability

Bean Scopes in Spring

A bean’s scope defines how long it lives and how it is shared.

1) Singleton Scope (Default)

@Service
public class UserService { }
  • One instance per Spring ApplicationContext
  • Shared across all requests and threads
  • Created eagerly by default (unless lazy)

Characteristics

  • Best for stateless services
  • Must be thread-safe
  • Lowest memory overhead

Default scope for ~95% of Spring beans

2) Prototype Scope

@Component
@Scope("prototype")
public class TaskContext { }
  • New instance created every time the bean is requested
  • Spring manages creation, not destruction

Important Caveat
Spring does not call lifecycle callbacks (@PreDestroy) for prototype beans.

When to use

  • Short-lived stateful objects
  • Per-task or per-operation context holders

3) Request Scope (Web Applications)

@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class RequestMetadata { }
  • One instance per HTTP request
  • Automatically destroyed at request completion

Use cases

  • Request tracing IDs
  • Per-request metadata
  • Authentication context wrappers

4) Session Scope

@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION)
public class UserSessionState { }
  • One instance per HTTP session
  • Lives until session expires or invalidates

Caution

  • Can increase memory usage
  • Avoid heavy objects

5) Application Scope

@Component
@Scope(WebApplicationContext.SCOPE_APPLICATION)
public class AppMetricsRegistry { }
  • One instance per ServletContext
  • Shared across all users and sessions

Typical usage

  • Caches
  • Metrics collectors
  • Feature flags

Bean Scope Comparison (Quick Reference)

ScopeInstance CountThread Safety RequiredTypical Use
Singleton1 per contextYesServices, repositories
PrototypeNew per requestNoTask-specific objects
Request1 per HTTP requestNoRequest metadata
Session1 per HTTP sessionNoUser session state
Application1 per appYesShared infrastructure

How Bean Scope Affects Concurrency

  • Singleton beans must be thread-safe
  • Prototype/request/session beans can hold mutable state
  • Mixing scopes incorrectly (e.g., injecting request-scoped beans into singletons) requires proxying

Example:

@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)

Spring uses proxies to resolve scope mismatches safely at runtime.

Production Best Practices

  • Default to singleton scope
  • Keep singleton beans stateless
  • Avoid session scope unless absolutely required
  • Use prototype beans only when lifecycle is clearly controlled
  • Always consider thread-safety implications

Spring Bean Lifecycle Overview

Spring beans follow a well-defined lifecycle:

  1. Instantiation
  2. Dependency injection
  3. Aware callbacks
  4. @PostConstruct
  5. Ready for use
  6. @PreDestroy

Spring Bean Lifecycle

Spring Bean lifecycle diagram showing instantiation, dependency injection, aware callbacks, @PostConstruct initialization, bean ready state, and @PreDestroy destruction phase.

Beans are:

  • Created once at startup (singleton scope by default)
  • Reused across requests
  • Destroyed on application shutdown

This is critical for managing:

  • Database connections
  • Thread pools
  • Messaging consumers

7. ApplicationContext vs BeanFactory (Why the Difference Matters)

WebApplicationContext

  • A specialized ApplicationContext
  • Bound to the Servlet lifecycle
  • Accessible by DispatcherServlet

In web applications, Spring uses WebApplicationContext:

Each DispatcherServlet owns its own WebApplicationContext, enabling modular and layered systems.

8. Spring Annotations — A Practical, Architectural Reference

Core Stereotype Annotations (Component Model)

These annotations define what role a class plays in the application.

AnnotationPurposeInternals / Notes
@ComponentGeneric Spring-managed beanBase stereotype
@ServiceBusiness logic layerSemantic specialization
@RepositoryPersistence layerEnables exception translation
@ControllerMVC controllerReturns views
@RestControllerREST API controller@Controller + @ResponseBody
@ConfigurationJava-based configurationEnables CGLIB proxying

Why These Matter Internally

  • All are discovered via classpath scanning
  • Registered as BeanDefinition objects
  • Enable consistent architectural boundaries
  • Improve maintainability and tooling intelligence

Dependency Injection Annotations

These annotations control how objects are wired together.

AnnotationUsageNotes
@AutowiredAutomatic dependency injectionConstructor preferred
@QualifierResolve multiple bean candidatesUsed with @Autowired
@PrimaryDefault bean selectionOverrides ambiguity
@ValueInject propertiesSupports SpEL

Example:

@Autowired
@Qualifier("fastPaymentProcessor")
private PaymentProcessor processor;

Bean Lifecycle & Scope Annotations

These annotations affect creation, lifecycle, and scope.

AnnotationPurpose
@BeanExplicit bean creation
@ScopeBean scope definition
@LazyDeferred initialization
@PostConstructInitialization callback
@PreDestroyCleanup callback

Example:

@Bean
@Scope("prototype")
public TaskContext taskContext() {
    return new TaskContext();
}

Web & REST Annotations (Spring MVC)

These annotations drive request mapping and dispatching, eventually routing through DispatcherServlet.

AnnotationPurpose
@RequestMappingBase request mapping
@GetMapping / @PostMappingHTTP method mappings
@PathVariableURI path binding
@RequestParamQuery parameter binding
@RequestBodyRequest payload binding
@ResponseBodyDirect response serialization

Example:

@RestController
@RequestMapping("/api/users")
public class UserController {

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.findById(id);
    }
}

This section naturally links to your REST API Performance Optimization article when discussing controllers and request handling.

Configuration & Bootstrapping Annotations

These annotations define how Spring Boot starts and configures the application.

AnnotationPurpose
@SpringBootApplicationBoot entry point
@EnableAutoConfigurationAuto-configure beans
@ComponentScanPackage scanning
@ImportImport configurations

Internally:

  • Triggers SpringApplication.run()
  • Loads ApplicationContext
  • Applies conditional auto-configurations

Conditional & Profile-Based Annotations

Used to control environment-specific behavior.

AnnotationPurpose
@ProfileActivate beans per environment
@ConditionalOnPropertyProperty-driven config
@ConditionalOnClassClasspath-driven config
@ConditionalOnMissingBeanDefault auto-config

These are heavily used in Spring Boot auto-configuration modules.

AOP & Cross-Cutting Concerns

These annotations enable proxy-based behavior.

AnnotationPurpose
@AspectDefine cross-cutting logic
@Before / @AfterAdvice hooks
@AroundMethod interception
@TransactionalTransaction boundaries

Example:

@Transactional
public void processOrder(Order order) {
    // database operations
}

Internally:

  • Spring creates dynamic proxies
  • Intercepts method calls
  • Applies behavior before/after invocation

Security Annotations (Spring Security)

These annotations integrate authorization and authentication.

AnnotationPurpose
@EnableWebSecurityEnable security filters
@PreAuthorizeMethod-level security
@SecuredRole-based checks
@AuthenticationPrincipalAccess current user

Example:

@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) { }

Annotation Design Principles (Why This Model Scales)

  • Declarative over imperative
  • Metadata-driven configuration
  • Enables tooling, IDEs, and AI understanding
  • Reduces boilerplate while preserving clarity

Spring annotations are not just syntax sugar — they are instructions to the container.

9. Spring MVC — Web and REST Layer

Spring MVC is responsible for:

  • HTTP request routing
  • Controller mapping
  • Validation
  • Serialization and deserialization

Typical REST Controller

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @GetMapping("/{id}")
    public OrderDto getOrder(@PathVariable Long id) {
        return service.getOrder(id);
    }
}

Spring MVC internally uses:

  • DispatcherServlet
  • HandlerMapping
  • HandlerAdapter
  • HttpMessageConverters

Why This Matters in Production

Controller design alone is not enough.
Concurrency, caching, and IO patterns directly affect latency and throughput.

👉 REST API Performance Optimization: Concepts, Tradeoffs, and Best Practices

10. How Servlet Mapping Works in Spring Boot

Spring Boot applications are still Servlet-based under the hood.

Even without web.xml, the Servlet model remains fundamental.

HTTP Request Flow

  1. Embedded Servlet container (Tomcat/Jetty/Undertow) receives the request
  2. Request is routed to DispatcherServlet
  3. Handler mappings locate the controller
  4. Controller method executes
  5. Response is serialized and returned

How Servlet Mapping Works in Spring Boot

Spring Boot simply automates servlet registration.

11. Request Filtering in Spring — Servlet Filters vs Spring Filters vs Spring Security

In a Spring Boot web application, every HTTP request passes through multiple interception layers before reaching a controller. Understanding where each interception mechanism runs is critical for security, performance, and debugging.

At a high level, request interception happens at three distinct layers:

  1. Servlet Filters (container-level)
  2. Spring MVC Interceptors (framework-level)
  3. Spring Security Filters (security filter chain)

Although these mechanisms are sometimes confused, they serve different purposes and run at different stages of request processing.

1) Servlet Filters (Container-Level)

Servlet filters are part of the Servlet specification, not Spring. They run before Spring MVC is involved and are managed by the servlet container (Tomcat, Jetty, Undertow).

Key Characteristics

  • Execute before DispatcherServlet
  • Operate on raw HttpServletRequest / HttpServletResponse
  • Applied to all requests, including static resources
  • Ideal for cross-cutting, infrastructure-level concerns

Typical Use Cases

  • Request/response logging
  • CORS handling
  • Compression
  • Low-level authentication
  • Request wrapping

Example: Simple Servlet Filter

@Component
public class LoggingFilter implements Filter {

    @Override
    public void doFilter(
            ServletRequest request,
            ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        System.out.println("Incoming request: " + httpRequest.getRequestURI());

        chain.doFilter(request, response);
    }
}

Servlet filters are framework-agnostic and run regardless of whether the request reaches a controller.

2) Spring MVC Interceptors (Framework-Level)

Interceptors are Spring MVC–specific and operate after the request enters Spring, but before controller methods are invoked.

Key Characteristics

  • Managed by Spring
  • Have access to handler (controller) metadata
  • Can run before and after controller execution
  • Do not wrap the response stream

Typical Use Cases

  • Authentication checks
  • Authorization logic
  • Request metrics
  • Locale resolution
  • Auditing

Execution Hooks

  • preHandle() — before controller
  • postHandle() — after controller
  • afterCompletion() — after request completion

Example: HandlerInterceptor

@Component
public class RequestTimingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        request.setAttribute("startTime", System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) {
        long duration = System.currentTimeMillis()
                - (long) request.getAttribute("startTime");
        System.out.println("Request took " + duration + " ms");
    }
}

3) Spring Security Filters (Security Layer)

Spring Security uses a dedicated filter chain built on top of Servlet filters, not interceptors.

This is one of the most important architectural distinctions.

Key Characteristics

  • Implemented as Servlet filters
  • Executed before DispatcherServlet
  • Ordered filter chain (SecurityFilterChain)
  • Responsible for authentication and authorization

Why Spring Security Uses Filters

  • Security must be applied before business logic
  • Authentication should happen before controllers
  • Works even when controllers are not invoked

Spring Security Filter Chain (Conceptual Flow)

Incoming Request
      ↓
Servlet Container
      ↓
Spring Security Filter Chain
      ↓
DispatcherServlet
      ↓
Spring MVC Interceptors
      ↓
@RestController

Authentication and authorization must succeed before the request reaches your controllers.

Example: Spring Security Filter in Action

When you configure Spring Security:

@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            )
            .httpBasic();

        return http.build();
    }
}

Internally, Spring Security:

  • Builds a filter chain
  • Registers it with the servlet container
  • Applies filters such as:
    • UsernamePasswordAuthenticationFilter
    • SecurityContextPersistenceFilter
    • AuthorizationFilter

Each filter performs one well-defined security responsibility.

Filter vs Interceptor vs AOP — Quick Comparison

MechanismLayerExecutes Before ControllerTypical Use
Servlet FilterServlet containerYesLogging, CORS, compression
Spring InterceptorSpring MVCYesAuth checks, metrics
Spring Security FilterServlet containerYesAuthentication, authorization
Spring AOPProxy-basedNoTransactions, logging

Why This Distinction Matters in Production

  • Misplacing logic can cause security gaps
  • Filters impact all traffic, including static assets
  • Interceptors are better for application-level logic
  • Security filters must run as early as possible

A common mistake is trying to perform authentication in controllers or interceptors, which is too late in the request lifecycle.

Best Practices Summary

  • Use Servlet filters for infrastructure-level concerns
  • Use Spring Interceptors for request-aware application logic
  • Use Spring Security filters for authentication and authorization
  • Avoid putting cross-cutting concerns directly in controllers

12. Spring ORM — Data Access Layer

Spring ORM integrates with:

  • JPA / Hibernate
  • JDBC
  • MyBatis

Benefits:

  • Declarative transactions
  • Consistent exception translation
  • Cleaner repository abstractions
@Repository
public interface OrderRepository
        extends JpaRepository<Order, Long> {
}

Spring manages the entire persistence lifecycle.

13. Transactions via AOP

Spring uses AOP proxies to apply transactions.

@Transactional
public void placeOrder() {
    saveOrder();
    chargePayment();
}

Transaction boundaries are applied without polluting business logic.

14. Spring Security — Authentication and Authorization

Spring Security provides:

  • Authentication
  • Authorization
  • CSRF protection
  • OAuth2 and JWT support
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser() {}

Used extensively in enterprise and microservice architectures.

15. Spring Messaging — Event-Driven Systems

Spring integrates with:

  • Kafka
  • RabbitMQ
  • JMS
@KafkaListener(topics = "orders")
public void consume(OrderEvent event) {}

Messaging enables loose coupling and scalable, event-driven design.

16. Spring Concurrency and Async Execution

Spring integrates with Java concurrency primitives.

@Async
public void processAsync() {}

Under the hood:

  • Uses ExecutorService
  • Managed by Spring
  • Lifecycle-aware

👉 ExecutorService & Thread Pools in Java — A Practical Guide

17. Spring Boot Auto-Configuration (What Actually Happens)

Spring Boot startup sequence:

  1. Scan classpath
  2. Load conditional auto-configurations
  3. Register beans
  4. Start embedded server

Spring Boot Startup Flow

@SpringBootApplication
        ↓
SpringApplication.run()
        ↓
Create ApplicationContext
        ↓
Load Auto-configurations
        ↓
Register Beans
        ↓
Start Embedded Server

Auto-configurations are declared in META-INF/spring.factories.

Nothing is hidden — everything is overrideable.

18. When to Use Spring vs Spring Boot

ScenarioRecommendation
MicroservicesSpring Boot
REST APIsSpring Boot
Cloud-native appsSpring Boot
Legacy XML systemsSpring Framework
Custom containersSpring Framework

Modern enterprise systems overwhelmingly choose Spring Boot.

Conclusion

Spring Boot and Spring Framework are often used interchangeably, but they serve distinct and complementary roles in modern Java applications.

Spring Framework provides the foundational container, programming model, and infrastructure services such as dependency injection, bean lifecycle management, transactions, AOP, and modular integration.
Spring Boot builds on top of this foundation to simplify configuration, standardize application startup, and provide production-ready defaults without changing how Spring works internally.

Understanding Spring at an architectural level means understanding:

  • how ApplicationContext manages beans and lifecycle
  • how BeanFactory differs from higher-level containers
  • how DispatcherServlet routes HTTP requests
  • how core modules like MVC, ORM, AOP, Security, Messaging, and Concurrency interact
  • how Spring Boot automates, but does not hide, these mechanisms

This knowledge is not academic. It directly affects performance, scalability, reliability, and debuggability in real-world systems. Developers who understand Spring internals can reason about application behavior under load, diagnose production issues faster, and design systems intentionally rather than relying on defaults.

In short, Spring Framework defines the architecture, and Spring Boot defines the execution model. Together, they form a powerful, flexible ecosystem for building enterprise-grade Java applications that scale over time.

This level of understanding is what transforms a developer from a framework user into a system designer.

TL;DR: Spring Framework provides the core container and programming model, while Spring Boot simplifies configuration and runtime behavior without changing Spring internals.

Spring Boot Startup Lifecycle (Deep Dive)

Spring Boot follows a well-defined startup sequence from main() execution to a fully initialized application context and running web server.

A detailed, step-by-step breakdown of the Spring Boot startup lifecycle — including lifecycle hooks, auto-configuration decisions, and common production pitfalls — will be published soon.

👉 Spring Boot Startup Lifecycle — From main() to a Ready Application (coming soon)

FAQ — Spring Boot & Spring Framework

What is the difference between Spring Framework and Spring Boot?

Spring Framework provides the core programming model, dependency injection container, and modular infrastructure for building Java applications. Spring Boot builds on top of Spring Framework and simplifies application setup by providing auto-configuration, embedded servers, opinionated defaults, and production-ready features without changing Spring’s internal architecture.

Does Spring Boot replace Spring Framework?

No. Spring Boot does not replace Spring Framework. Spring Boot uses Spring Framework internally and only removes the need for manual configuration. All core concepts—ApplicationContext, BeanFactory, dependency injection, AOP, and transactions—remain exactly the same.

How does Spring Boot auto-configuration work?

Spring Boot auto-configuration works by conditionally creating beans based on the classpath, existing beans, and application properties. It uses @EnableAutoConfiguration and @Conditional annotations to activate configurations only when certain conditions are met, reducing boilerplate configuration.

What happens when a request hits a Spring Boot application?

When a request arrives, the embedded servlet container (Tomcat, Jetty, or Undertow) routes it to Spring’s DispatcherServlet. The DispatcherServlet identifies the appropriate controller via handler mappings, invokes the method annotated with @RestController or @Controller, applies interceptors and filters, and returns the response through message converters.

How does servlet mapping work in Spring Boot?

Spring Boot automatically registers the DispatcherServlet and maps it to / by default. This mapping is configurable via application properties. All incoming HTTP requests are routed through the DispatcherServlet unless explicitly excluded.

What is ApplicationContext in Spring?

ApplicationContext is the central interface of the Spring container responsible for managing beans, handling dependency injection, publishing application events, resolving resources, and integrating cross-cutting concerns like AOP and transactions. It extends BeanFactory with enterprise-level features.

What is the difference between BeanFactory and ApplicationContext?

BeanFactory provides basic dependency injection and lazy bean creation. ApplicationContext builds on BeanFactory by adding features such as eager bean initialization, event propagation, internationalization, and integration with Spring AOP and web frameworks.

How does Spring manage bean lifecycle?

Spring manages the bean lifecycle through defined phases: instantiation, dependency injection, initialization callbacks, post-processing, usage, and destruction. Developers can hook into this lifecycle using annotations like @PostConstruct, @PreDestroy, and interfaces such as InitializingBean.

What modules are included in the Spring ecosystem?

The Spring ecosystem includes modules such as Spring Core, Spring MVC, Spring Data (JPA, JDBC, MongoDB), Spring Security, Spring AOP, Spring Messaging, Spring Integration, Spring Batch, and Spring WebFlux. Spring Boot provides starters to simplify using these modules together.

When should I use Spring MVC vs Spring WebFlux?

Spring MVC is suitable for traditional synchronous, servlet-based applications. Spring WebFlux is designed for reactive, non-blocking applications handling high concurrency with fewer threads. Choose WebFlux when scalability and reactive streams are primary requirements.

How does Spring handle concurrency?

Spring delegates concurrency management to Java’s concurrency primitives and executors. It provides abstractions such as @Async, task executors, scheduling support, and seamless integration with ExecutorService and thread pools for controlled asynchronous processing.

Is Spring Boot suitable for large-scale enterprise applications?

Yes. Spring Boot is widely used in large-scale enterprise systems. It improves developer productivity while still allowing full control over architecture, performance tuning, security, concurrency, and deployment strategies.

How does Spring Boot support production readiness?

Spring Boot provides production-ready features through Spring Boot Actuator, including health checks, metrics, logging, tracing, and environment configuration. These features make Spring Boot suitable for cloud-native and microservice architectures.

How does Spring Boot relate to REST API performance?

Spring Boot simplifies building REST APIs, while performance depends on controller design, serialization, thread pool sizing, database access patterns, and caching. For deeper performance considerations, see:
👉 REST API Performance Optimization: Concepts, Tradeoffs, and Best Practices

Should I learn Spring Framework before Spring Boot?

Understanding Spring Framework fundamentals—dependency injection, ApplicationContext, bean lifecycle, and AOP—makes learning Spring Boot easier. Spring Boot abstracts configuration, but foundational Spring concepts remain essential for debugging and architecture decisions.

Why is Spring still relevant in modern Java development?

Spring remains relevant because it provides a mature, extensible, and battle-tested foundation for building scalable Java applications. Spring Boot modernizes Spring usage without discarding its proven architecture.

Related Articles

References

This article is based on official Spring documentation and established enterprise architecture practices.

Spring Architecture References

Did this tutorial help you?

If you found this useful, consider bookmarking Code & Candles or sharing it with a friend.

Explore more tutorials

Leave a Comment

Your email address will not be published. Required fields are marked *