Wednesday, 25 June 2025

Internal flow of spring boot/spring/spring mvc

The internal flow of Spring Boot refers to what happens behind the scenes when you run a Spring Boot application β€” from startup to handling requests. 


πŸ” 1. Application Startup (main() method)

@SpringBootApplication

public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }

When you run a Spring Boot application using the entry point(SpringApplication.run(...)) then bootstraps the entire Spring Boot application

  • And creates a SpringApplication object.

  • And sets up:

    • Environment (like application.properties)

    • ApplicationContext (Spring Container)

    • Auto-configuration

    • Logging system

    • Banner display

    • Listeners and initializers


πŸ”§ 2. Component Scan & Bean Creation

Triggered by:

java
@SpringBootApplication // = @Configuration + @ComponentScan + @EnableAutoConfiguration

Internals:

  • And ComponentScan internally scans all classes under the base package and sub-packages.

  • Registers beans for:

    • @Component, @Service, @Repository, @Controller, @RestController

  • Spring’s BeanFactory or ApplicationContext creates and manages the lifecycle of these beans.

  • Dependency injection using @Autowired, @Value, @Qualifier, etc.


βš™οΈ 3. Auto Configuration

Provided by:

java
@EnableAutoConfiguration

Internals:

  • Uses spring.factories to load classes annotated with @Configuration.

  • Auto-configures beans (like DataSource, Kafka, MVC, etc.) based on classpath and properties.

  • Uses conditional annotations like:

    • @ConditionalOnClass

    • @ConditionalOnMissingBean

    • @ConditionalOnProperty


πŸ›  4. Initialization of Embedded Server

Example:

  • Tomcat (default), Jetty, or Undertow

Internals:

  • Spring Boot auto-configures and starts the embedded server.

  • DispatcherServlet is initialized and mapped to handle all requests (/).

  • Servlet context is set up.


🌐 5. Request Handling (Web Layer)

Steps:

  1. HTTP request hits the embedded server (Tomcat).

  2. Routed to the DispatcherServlet.

  3. DispatcherServlet uses HandlerMapping to find the correct controller method.

  4. Executes:

    • HandlerInterceptors

    • Controller method (e.g., @GetMapping, @PostMapping)

  5. Returns the result (ResponseEntity, JSON, View).

  6. DispatcherServlet sends response back to the client.


πŸ“¦ 6. Persistence Layer (If Configured)

  • Auto-configures:

    • DataSource (JDBC or JPA)

    • Hibernate EntityManager

    • Repositories via @Repository and @EnableJpaRepositories

  • Transaction management via @Transactional


πŸ“Š 7. Actuator & Monitoring (Optional)

  • Spring Boot Actuator auto-configures endpoints for:

    • /actuator/health

    • /actuator/info

    • /actuator/metrics

  • Useful for health checks and integration with Prometheus/Grafana


πŸ›‘ 8. Shutdown Flow

  • Triggers graceful shutdown:

    • Calls SmartLifecycle.stop()

    • Closes ApplicationContext

    • Releases resources (e.g., DB connections, Kafka consumers)

  • Beans with @PreDestroy or implementing DisposableBean are cleaned up.


βš™οΈ Internal Components Summary

ComponentRole
SpringApplicationBootstraps and configures the application
ApplicationContextManages beans and dependency injection
DispatcherServletFront controller for web requests
BeanPostProcessorAllows custom modification of beans
@ConfigurationDeclares Spring configurations
@EnableAutoConfigurationEnables Spring Boot’s intelligent auto setup
CommandLineRunner / ApplicationRunnerExecutes code after startup      

πŸ” Spring Boot Internal Flow

βœ… Visual Diagram + Call Stack Trace


πŸ“Œ A. Visual Architecture Diagram of SpringApplication.run(...)


+------------------------------------------------------+ | Your Application Class | | @SpringBootApplication | | public class MyApp { | | public static void main(String[] args) { | | SpringApplication.run(MyApp.class, args); | | } | | } | +---------------------------|--------------------------+ | v +----------------------------[SpringApplication.run()]-----------------------------+ | | | 1. Create SpringApplication instance | | - Set application type (Servlet, Reactive, None) | | - Load initializers and listeners (from spring.factories) | | | | 2. Prepare Environment | | - Load `application.properties`, profiles, command-line args, env vars | | - Configure ConfigurableEnvironment | | | | 3. Create ApplicationContext (IoC container) | | - e.g., AnnotationConfigServletWebServerApplicationContext | | | | 4. Refresh ApplicationContext (Spring Core) | | - Call AbstractApplicationContext.refresh() | | a. Prepare BeanFactory | | b. Load Bean Definitions (via classpath scanning) | | c. Register BeanPostProcessors | | d. Instantiate Singleton Beans | | e. Inject Dependencies (`@Autowired`, etc.) | | f. Apply Lifecycle Callbacks (`@PostConstruct`, AOP proxies, etc.) | | | | 5. Run ApplicationRunner / CommandLineRunner | | | | 6. Publish ApplicationReadyEvent | +----------------------------------------------------------------------------------+ | v πŸš€ Application is Ready to Handle Requests

πŸ“Œ B. Internal Call Stack Trace

(Important Classes and Methods Behind the Scenes)


java
// Entry point SpringApplication.run(MyApp.class, args) // β†’ Step 1: Constructor new SpringApplication(MyApp.class) └── setInitializers() └── setListeners() └── deduceApplicationType() // β†’ Step 2: Run method SpringApplication.run() └── prepareEnvironment() └── configurePropertySources() └── bindEnvironmentProperties() └── printBanner() └── createApplicationContext() └── AnnotationConfigServletWebServerApplicationContext └── prepareContext() └── applyInitializers() └── listeners.contextPrepared() └── refreshContext() β†’ context.refresh() // β†’ Step 3: Spring Core Container (IoC) AbstractApplicationContext.refresh() └── prepareBeanFactory() └── invokeBeanFactoryPostProcessors() └── registerBeanPostProcessors() └── initMessageSource() └── initApplicationEventMulticaster() └── onRefresh() // For web apps: create embedded Tomcat, setup dispatcher └── registerListeners() └── finishBeanFactoryInitialization() └── create all singleton beans └── apply dependency injection └── finishRefresh() // β†’ Step 4: Call ApplicationRunners └── callRunners(context, args) └── invoke all ApplicationRunner & CommandLineRunner beans // β†’ Step 5: Events Published └── ApplicationStartedEvent └── ApplicationReadyEvent

πŸ“¦ Summary Diagram:

SpringApplication.run() | └── Create SpringApplication instance | └── Prepare Environment | └── Create ApplicationContext (Spring Container) | └── refresh() β”œβ”€β”€ Load bean definitions β”œβ”€β”€ Instantiate beans β”œβ”€β”€ Inject dependencies └── Apply lifecycle methods | └── Application is ready

βœ… Key Classes Involved:

ComponentResponsibility
SpringApplicationEntry point for bootstrapping the app
ConfigurableApplicationContextSpring’s container holding all beans
ApplicationContextInitializerModify context before refresh
BeanFactoryPostProcessorModify BeanFactory before beans instantiated
BeanPostProcessorModify beans after instantiation
AnnotationConfigServletWeb...CtxIoC + embedded web server (Tomcat)
@SpringBootApplicationCombo of @Configuration, @ComponentScan, @EnableAutoConfiguration
ApplicationRunner, CommandLineRunnerCode to run just before app is ready

πŸ“Œ Optional: View Actual SpringApplication.run() Flow in Debug Mode

Set a breakpoint in your IDE:

java
SpringApplication.run(MyApp.class, args);

And then step into to trace each class mentioned above.

SpringApplication class in Spring Boot

βœ… SpringApplication is a class in Spring Boot that is responsible for bootstrapping and launching a Spring application from the main() method. It sets up the Spring ApplicationContext, performs auto-configuration, and starts the embedded server (like Tomcat).


πŸ“Œ Simple Definition:

SpringApplication is the entry point used to start a Spring Boot application.


🧱 Syntax:

java
SpringApplication.run(ApplicationClass.class, args);

πŸ”§ Example:

java
@SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }

πŸ” What It Does Internally:

  1. Creates an ApplicationContext

  2. Loads beans and applies auto-configuration

  3. Sets up logging, environment, and banner

  4. Starts embedded web server (Tomcat/Jetty/Undertow)

  5. Runs any CommandLineRunner or ApplicationRunner beans


πŸ”© Advanced Usage:

java
SpringApplication app = new SpringApplication(MyApplication.class); app.setBannerMode(Banner.Mode.OFF); app.run(args);

πŸ“š Key Features:

  • Auto-configuration

  • Environment loading (application.properties/yaml)

  • Command line argument parsing

  • Banner control

  • Listener and event publishing support

---------------------------

βœ… 2. Spring Framework Internal Flow

🌱 Spring Core Container Flow

  • IoC Container (Inversion of Control):

    • Reads configuration (@Configuration, @Component)

    • Instantiates beans

    • Resolves dependencies via:

      • @Autowired, @Qualifier, @Primary, XML, etc.

πŸ”„ Bean Lifecycle:

  1. Instantiation

  2. Populate properties (@Autowired, setters)

  3. BeanNameAware, BeanFactoryAware callbacks

  4. InitializingBean.afterPropertiesSet() or @PostConstruct

  5. Bean is ready to use

  6. On shutdown: @PreDestroy or DisposableBean.destroy()


βœ… 3. Spring MVC Internal Flow

🌐 HTTP Request Flow (Spring Web MVC DispatcherServlet)

text
Client -> Embedded Tomcat -> DispatcherServlet -> HandlerMapping -> Controller -> Service -> Repository -> DB <- ResponseBody/ModelAndView <- ViewResolver <- DispatcherServlet <- Client

πŸ” Step-by-step Request Flow:


πŸ”Ή 1. Client Sends HTTP Request

Example: GET /users/123


πŸ”Ή 2. DispatcherServlet (Front Controller)

  • Configured by Spring Boot auto-config.

  • Intercepts all incoming requests (/ mapping).

  • Delegates request to appropriate components.


πŸ”Ή 3. HandlerMapping

  • Finds appropriate @Controller class & method based on URL and HTTP method.

  • Ex: @GetMapping("/users/{id}")


πŸ”Ή 4. HandlerAdapter

  • Executes the controller method.


πŸ”Ή 5. Controller Method

java
@GetMapping("/users/{id}") public ResponseEntity<User> getUser(@PathVariable int id) { return ResponseEntity.ok(userService.findById(id)); }
  • Calls the Service layer.

  • Business logic executes.


πŸ”Ή 6. Service Layer

  • Contains business logic

  • Calls the Repository (DAO)


πŸ”Ή 7. Repository Layer

  • Interacts with the DB using JPA/Hibernate.

java
@Repository public interface UserRepository extends JpaRepository<User, Integer> {}

πŸ”Ή 8. Return Response

  • Controller returns ResponseEntity or object.

  • If annotated with @RestController or @ResponseBody, data is serialized (JSON/XML) by HttpMessageConverters (like Jackson).


πŸ”Ή 9. ViewResolver (If using Thymeleaf/JSP)

  • If returning a view name, ViewResolver resolves it to an actual .html or .jsp.


πŸ”Ή 10. Response Sent to Client


βœ… Internal Objects in Spring MVC

ComponentPurpose
DispatcherServletCentral controller of Spring MVC
HandlerMappingFinds which controller to call
HandlerAdapterCalls the actual controller method
HttpMessageConverterConverts object to JSON/XML
ViewResolverResolves view names to templates
ModelAndViewHolds model + view data
WebDataBinderBinds request params to Java objects

πŸ”š Summary Diagram

SpringApplication.run() ↓ Creates ApplicationContext ↓ Scans Beans (@Component, etc.) ↓ Initializes DispatcherServlet ↓ Starts Embedded Server (Tomcat) ↓ Client HTTP Request ↓ DispatcherServlet ↓ HandlerMapping β†’ Controller ↓ Service β†’ Repository β†’ DB ↓ Controller returns Response/ModelAndView ↓ HttpMessageConverter/ViewResolver ↓ Response back to Client

πŸ” Detailed Breakdown:

βœ… 1. SpringApplication.run(...) This is the entry point to boot your Spring Boot application. It performs: Environment preparation ApplicationContext creation Auto-configuration Running ApplicationRunner or CommandLineRunner beans Internally: java public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args)
βœ… 2. Creates ApplicationContext Based on the application type (web or non-web), it creates: AnnotationConfigServletWebServerApplicationContext (for Spring MVC) or another variant like ReactiveWebServerApplicationContext (for WebFlux) This is the Spring container that manages all beans and lifecycle. βœ… 3. Scans Beans (@Component, @Service, @Controller, etc.) Spring scans packages based on: @SpringBootApplication β†’ combines @ComponentScan Beans annotated with: @Component, @Service, @Repository, @Controller, @RestController These are registered in the ApplicationContext. βœ… 4. Initializes DispatcherServlet The DispatcherServlet is the Front Controller in Spring MVC. It is automatically registered as a bean and mapped to /. It handles all incoming HTTP requests. βœ… 5. Starts Embedded Server (Tomcat/Jetty/Undertow) Spring Boot uses embedded servers (default is Tomcat). The server is started programmatically, no need for web.xml. Example log: scss Tomcat started on port(s): 8080 (http)
βœ… 6. Client HTTP Request A user (browser/API client) makes an HTTP request: bash GET http://localhost:8080/users βœ… 7. DispatcherServlet DispatcherServlet intercepts the request. It is configured via WebMvcAutoConfiguration. It coordinates the request-handling workflow. βœ… 8. HandlerMapping β†’ Controller DispatcherServlet asks HandlerMapping for the correct controller. Finds a @RequestMapping, @GetMapping, etc. Then, calls the method in the controller class: java @RestController public class UserController { @GetMapping("/users") public List<User> getUsers() { ... } } βœ… 9. Service β†’ Repository β†’ DB The controller delegates logic to the @Service layer. The service calls the @Repository, which interacts with the database: java @Service public class UserService { @Autowired private UserRepository repo; public List<User> getAllUsers() { return repo.findAll(); } } βœ… 10. Controller returns Response or ModelAndView The controller returns: ResponseEntity<?> for REST Or ModelAndView for traditional MVC Spring uses this return type to decide how to process the response. βœ… 11. HttpMessageConverter / ViewResolver If REST: Uses HttpMessageConverter (e.g., Jackson) to convert Java objects β†’ JSON/XML If MVC: Uses ViewResolver to resolve .jsp or .html views βœ… 12. Response back to Client The generated response (JSON, HTML, etc.) is sent back via HTTP to the client: css HTTP 200 OK Content-Type: application/json Body: [{"id":1,"name":"John"}, ...] βœ… Summary Flow Diagram text SpringApplication.run() ↓ ApplicationContext created ↓ Beans scanned and registered ↓ Embedded server (Tomcat) started ↓ ↓ Client makes request DispatcherServlet receives it ↓ HandlerMapping β†’ Controller method ↓ Service β†’ Repository β†’ DB ↓ Controller returns response ↓ HttpMessageConverter or ViewResolver ↓ HTTP Response to client

No comments:

Post a Comment