- Architecture
Spring Boot Architecture – Detailed Explanation
What is spring boot, features of spring boot, spring initializr, autoconfiguration, externalized configuration.
- Spring Boot Architecture
Spring Boot Workflow Architecture
Advantages and disadvantages of spring boot architecture, disadvantage, additional resources.
Spring publishing is a sophisticated variant or job from the Spring framework. It is made up of third-party libraries and Embedded HTTP servers, in addition to the Spring framework. It produces high-quality, more time-consuming, and standalone apps that depend on the Spring framework. Spring Hack is working to eliminate the use of XML-based and annotation-based settings in software by default.
We will learn how this Spring Boot framework was designed in this tutorial. The above diagram illustrates that every layer of this structure is connected to the layer immediately above or below it because of the workflow. Every layer, therefore, only requires access to its proximate neighbours, so if we alter the API of a single layer, for example, we only need to upgrade the layers alongside it.
Spring Boot is an automated version of the traditional spring framework, simplifying and automating the process. Spring Boot is built on top of the Spring framework and is a layered structure in which every layer communicates with each other layer(from top to bottom in hierarchical order). The Spring Boot framework documentation provides the following definition.
Confused about your next job?
Spring Boot makes it possible to create high-quality, production-grade Spring applications that are simple to deploy and run.
Spring boot is designed to remove XML and annotations-based configuration settings from the application. Spring boot provides the following advantages, including opinionated(options to later change the configuration), convention over configuration, stand-alone, and production-ready: It provides stand-alone, production-ready, and convention over configuration options.
Spring Boot is a Java framework. It is built on the Spring framework and takes an apertures, opinionated, boilerplate-free approach to Spring applications. Spring Boot, however, does not require you to write excessive boilerplate code. The majority of Spring Boot applications, however, require minimal Spring configuration.
A Java developer who uses the auto-configuration feature can automatically configure his or her Spring application using jar dependencies, thereby making it very convenient for them to develop applications.
Spring Boot features that Java developers should be aware of are listed below:
Spring Boot projects are created through cURL, multiple IDEs, and the Spring CLI using Spring Initializr. Spring Boot is a Spring feature that enables project creation using cURL. Spring CLI, Spring IDEs, and the Spring CLI all support the Spring Boot feature. It doesn’t generate any application code but provides a basic project structure. All you need to do is write the application code.
Spring Initializr enables you to select a project, the programming language of your choice, and add dependencies such as development tools, actuators, web pages, and so on. To create a project, you must just click the Generate button after selecting the options on the Spring Initializr screen.
The project includes the Gradle build specification or pom.xml, depending on which Gradle or Maven project you chose to build, respectively. In addition to that, it includes a class with a main () method that boots up the application. Spring Boot is used to auto-configure the application context and set empty properties.
The Spring Boot CLI is a command line tool that you can use to create Spring applications quickly. By using Spring CLI, you can code Java-based applications by using your Java knowledge, even if you don’t write reusable code repeatedly. The starter component resolves dependencies when you start a new project.
To use the Initializr to kick-start development on a Java project on a more traditional project, you must first use this Spring Boot feature. The init command is, for instance, a way to use the Initializr to create a baseline project. The resulting zip file has the project structure, which you can then add or remove as you please. If not, you can modify the code as well.
The autoconfiguration feature provided by Spring Boot can help you develop and integrate your code but you still need to manually configure a lot of things. Now imagine you want to create a new library that you will use at different locations in your application. You can develop and integrate the code, but you may still be required to manually configure a lot of things.
It is possible to choose dependencies for a new Spring Boot project. These dependencies, based on which the autoconfiguration feature loads specific default configurations, are evaluated by Spring Boot during application startup. The AutoConfiguration class is fortified with @Conditional annotations that activate beans in particular circumstances, and the @Conditional annotation is used to activate beans in certain circumstances.
To use Spring’s conditional annotations, we must refer to the reference documentation. If our usage scenario does not require these conditions, you may create your own custom ones.
You must use @EnableAutoConfiguration or @SpringBootApplication annotations to use autoconfiguration.
All Spring Boot properties are read from the application properties or application YAML in Spring Boot applications. However, there may be circumstances where you wish to move your configuration from one environment to another. This is where you may need to configure these properties. You must rebuild and retest your application in all environments whenever you modify these variables. Furthermore, every time a change is made, you must also restart your application in production.
Spring Boot allows you to externalize your configuration by coding your application code as if it were used in one environment and then in another environment. You can reuse your application code in diverse environments by externalizing your configuration. You can externalize your configuration to use the code you created in one environment as a starting point. You can export your configuration as follows:
- Properties files
- Environment variables, etc.
You may need to understand what is happening inside an application in order to debug it or log it. For example, how many times a specific service was contacted, or how often a specific service failed. The Actuator framework is an easy-to-use framework you can use without installing another application or tool to inspect your application health-check endpoints. Spring Actuator is a lightweight means to track health, metrics, information, and so on.
You can interact with Actuator endpoints in Spring Boot, as well as those provided by Spring. Spring Boot includes a variety of built-in actuator endpoints and actuator implementations, so you can either add your own actuators or use the ones provided.
Spring Boot is a specialised part of the Spring Framework. It is utilised to create high-quality, production-grade Spring Based Applications with minimal effort. Spring Framework code is used to create Spring Boot.
Spring Boot uses a hierarchical architecture in which each layer communicates with the layer immediately below or above it ( hierarchical structure).
Before getting to the Spring Boot Architecture, we must first understand what each of those layers and classes means. The four layers in Spring Boot are as follows:
- Presentation Layer
- Business Layer
- Persistence Layer
- Database Layer
The following information is provided about these layers:
Presentation Layer: A JSON structure is made up of viewpoints. A front layer is what is seen from the outside and a back layer is where the structure is built from viewpoints. It interprets JSON and handles authentication and HTTP requests. After authentication, it enters the business layer for further processing.
Business Layer: As part of business logic, it manages all of the business decisions and performs the business validation and consent. For example, only admins may modify the customer’s account.
Persistence Layer: All of the storage logic in this program, including database questions, is accounted for in this portion of code. It also translates between database rows and company items.
Database Layer: The structure is constructed in this way: The HTTP request or internet requests are handled by the Controllers from the demonstration layer, the providers control the company logic, as well as also the repositories preserve persistence (storage logic). Each provider, service, and repository may be controlled by a single Controller. There are many repositories, which may be managed by many repositories, and databases may be managed by many databases.
Spring Boot relies heavily on the Spring framework, which means that it integrates almost all of the features and modules of Spring-like Spring MVC, Spring Core, and so on, but there is no demand for your DAO and DAOImpl classes.
Explanations:
- Validator classes, view classes, and utility classes have been defined.
- Spring Boot employs the same modules as Spring-like Spring MVC, Spring Data, and so on, but it has a different architecture. Spring Boot is the same as Spring MVC, but the one difference is that no DAO and DAOImpl classes are required.
- Temporarily blocks an operation in order to create a data access layer and perform CRUD operations.
- The client handles the HTTP requests (PUT or GET).
- The controller receives the request, and it handles it. Then, it passes the request to the service logic if necessary.
- All business logic is implemented in the service layer. It performs the logic on the data that is mapped to JPA using model classes.
- An error is not reported to the user when a JSP page is returned to the application.
The following are the benefits and limitations listed:
- Spring Boot allows for quick and easy development of spring-based applications in Java or Groovy.
- Spring Boot optimizes for reduced time. It reduces the time spent developing and increasing productivity.
- By reducing all the manual labour involved in writing annotations, boilerplate codes and XML configurations, it also helps in reducing the risk of errors.
- The Spring Boot Application with Spring Ecosystem, which includes Spring Security, Spring Data, Spring JDBC and Spring ORM, is now easy to integrate with Spring.
- It would also be easier for developers to follow the ‘Opinionated Defaults Configuration’
- Development Web apps can be tested using Embedded HTTP servers such as Jetty, Tomcat, and also conveniently rely on them.
- The Spring Boot CLI is accessible through the Command Line Interface, which has been and is being developed and tested in Spring Boot applications written in Java or Groovy.
- Spring Boot can be built with the aid of tools like Gradle and Maven, as well as the jBOSS. Alongside, it provides a lot of plugins that make effortless development and testing of Spring Boot applications possible.
- Working with embedded and memory databases is extremely convenient and easily accomplished with the plugin.
- There is no problem with converting legacy or existing Spring Framework projects to Spring Boot applications, however, the time involved in the process is critical.
- The size of the application deployment file is increased because of the high number of unused dependencies caused by Spring Boot.
- Becoming a Spring Boot application requires the time-consuming and complicated process of converting a legacy Spring project to a Spring Boot one.
- Many developers argue that Spring Boot is not suitable for building large-scale applications because it is unsuitable for working with microservices.
- Spring Boot works well with small applications, as it can be deployed directly into Docker containers. In a large and complex application, I’d rather not use Spring Boot.
Spring Boot is a development framework that is built on top of the Spring framework. We also learnt about the different layers in the Spring Boot architecture in this article. We also learnt about the flow in Spring Boot Architecture.
- Free Spring Boot Online Course
- Spring Boot Interview Questions
- Spring vs Spring Boot
- Difference Between Spring MVC and Spring Boot
Previous Post
Hive architecture – detailed explanation, sql server architecture – detailed explanation.
Architecture of Spring Boot: Examples, Pattern, Layered, Controller Layer
Varun Saharawat is a seasoned professional in the fields of SEO and content writing. With a profound knowledge of the intricate aspects of these disciplines, Varun has established himself as a valuable asset in the world of digital marketing and online content creation.
Master the architecture of Spring Boot with our insightful blog. We'll illustrate key concepts through examples, design patterns, and discuss the significance of a well-structured layered approach!
Architecture of Spring Boot: Several application development frameworks are available, but one of the most popular frameworks when working with Java is the Spring framework. You will be completely fascinated with the Spring framework and its ability to manage applications.
Spring Boot is a Spring Framework module. It is used to quickly construct standalone, production-grade Spring Based Applications. It is built on top of the Spring Framework. Spring Boot has a layered architecture in which each layer communicates with the layer below or above it.
In this article, we will learn about the architecture of Spring Boot. We will also learn about the different layers in the Spring boot architecture. We will also learn about flow in Spring Boot Architecture.
If you want to make a successful career in Full Stack Web Development, the PhysicsWallah’s Full Stack Web Development course is just what you need! Our course will equip you with all the necessary skills and knowledge needed to become a highly successful Full Stack Web Developer in 2024! So, don’t wait! Use the coupon code “ READER” and avail an exclusive discount on all PW Skills courses.
Table of Contents
Spring Boot Architecture Example
- Controller Layer:
- This layer is responsible for handling incoming HTTP requests.
- Controllers receive requests, process them, and interact with the service layer to retrieve or manipulate data.
- Controllers are often annotated with @Controller or @RestController.
- Service Layer:
- The service layer contains business logic and acts as an intermediary between the controller and the data access layer.
- It encapsulates the application’s business logic, ensuring separation of concerns.
- Services are often annotated with @Service.
- Repository/DAO Layer:
- This layer is responsible for interacting with the database or any external data source.
- It includes interfaces or classes that define methods for performing CRUD (Create, Read, Update, Delete) operations.
- Repositories are often annotated with @Repository.
- Entity Layer:
- Entities represent the application’s data model and are often mapped to database tables.
- These classes typically contain fields annotated with JPA annotations (@Entity, @Column, etc.) for database mapping.
- DTO (Data Transfer Object):
- DTOs are used to transfer data between layers and can help to encapsulate the data being sent between the client and the server.
- They can be used to shape the data for presentation without exposing the internal entity structure.
- Security Layer:
- This layer is responsible for handling authentication and authorization.
- Spring Security is commonly used to secure Spring Boot applications, providing features like authentication, authorization, and protection against common security vulnerabilities.
- Configuration Layer:
- This layer includes configuration files and classes.
- Configuration can be done using annotations like @Configuration, @Bean, or through XML configuration.
Remember that Spring Boot is highly customizable, and the architecture can be adapted based on project requirements. This overview provides a general structure that many Spring Boot applications follow.
Spring Boot Architecture Patterns
Spring Boot applications often follow certain architectural patterns to achieve modularity, scalability, and maintainability. Here are some common architectural patterns used in Spring Boot development:
- MVC (Model-View-Controller):
- Spring Boot follows the MVC pattern for building web applications.
- Model: Represents the application’s data and business logic.
- View: Responsible for rendering the user interface.
- Controller: Handles user requests, interacts with the model, and updates the view.
- Microservices Architecture:
- Spring Boot is commonly used in microservices architectures where the application is decomposed into small, independently deployable services.
- Each microservice is responsible for a specific business capability and communicates with other services through APIs.
- Restful API Design:
- Spring Boot promotes the design of RESTful APIs for communication between components.
- Controllers expose RESTful endpoints, and data is typically exchanged in JSON format.
- Layered Architecture:
- Organising the application into layers like presentation, service, repository, and entity helps maintain a separation of concerns.
- This layered architecture promotes modularity and testability.
- Dependency Injection (DI) / Inversion of Control (IoC):
- Spring Boot relies heavily on the principle of dependency injection, where dependencies are injected into components rather than being created by the components themselves.
- This reduces tight coupling and makes the application more maintainable.
- Event-Driven Architecture:
- Spring Boot supports event-driven architecture through the use of Spring Events.
- Components can publish and subscribe to events, allowing for loosely coupled communication between different parts of the application.
- CQRS (Command Query Responsibility Segregation):
- CQRS separates read and write operations, allowing for independent scaling of the query (read) and command (write) sides.
- Spring Boot can be used to implement CQRS patterns using different components for command and query responsibilities.
- Saga Pattern:
- In microservices architectures, the saga pattern is often used to manage distributed transactions.
- Spring Boot applications can implement sagas by coordinating a series of transactions across multiple microservices.
- Gateway Pattern:
- API gateways are used to manage and route requests in microservices architectures.
- Spring Cloud provides tools like Spring Cloud Gateway for building API gateways.
These patterns can be combined and adapted based on the specific requirements of the application. The flexibility of Spring Boot allows developers to choose and implement the patterns that best suit their needs.
Also Read: Algorithms In Java: List, Programs, Interview Questions
Spring Boot Layered Architecture Example
Let’s walk through a layered architecture example for a Spring Boot application without providing specific code. This example assumes a typical three-layered architecture: Presentation, Service, and Data Access layers.
- Presentation Layer:
- This layer handles the interaction with the user, receives HTTP requests, and sends responses.
- Controllers in this layer are annotated with @RestController.
- The controllers interact with the Service layer to process requests and obtain results.
- DTOs (Data Transfer Objects) may be used to transfer data between the Presentation and Service layers.
- The Service layer contains business logic and orchestrates the flow of data between the Presentation and Data Access layers.
- Service classes are annotated with @Service.
- They use the Data Access layer to retrieve or manipulate data.
- This layer is responsible for enforcing business rules and ensuring data consistency.
- Data Access Layer:
- The Data Access layer is responsible for interacting with the database or any other data source.
- It includes repository interfaces or classes annotated with @Repository.
- Entities represent the data model and are often annotated with JPA annotations for database mapping.
Example Workflow:
- A user sends an HTTP request to a REST endpoint in the Presentation layer.
- The controller in the Presentation layer receives the request and invokes the appropriate method in the Service layer.
- The Service layer performs business logic, possibly involving multiple service classes, and interacts with the Data Access layer to retrieve or persist data.
- The Data Access layer communicates with the database to perform CRUD operations on entities.
- The Service layer returns the result to the Presentation layer, possibly transforming entities into DTOs.
- The Presentation layer sends an HTTP response to the user.
- Modularity: Each layer has a specific responsibility, making the application more modular and easier to maintain.
- Separation of Concerns: The separation of layers allows for a clear distinction between presentation, business logic, and data access concerns.
- Testability: Each layer can be tested independently, promoting easier unit testing and maintenance.
- Scalability: Components can be scaled independently based on the specific needs of each layer.
Considerations:
- Care should be taken to avoid tight coupling between layers. Dependency injection and interfaces can help achieve loose coupling.
- DTOs may be used to transfer data between layers, but excessive use should be avoided to prevent overcomplicating the architecture.
Remember that this is a high-level overview, and specific project requirements may lead to variations in the architecture.
Architecture of Spring Boot Microservices
The architecture of Spring Boot microservices typically follows principles that align with the characteristics of microservices, such as modularity, independence, and distributed systems. Here’s a conceptual overview of the architecture for a Spring Boot microservices application:
- Microservices:
- The application is decomposed into small, independent, and loosely coupled services, each focused on a specific business capability.
- Microservices communicate with each other through well-defined APIs, often exposed as RESTful endpoints.
- Service Registry and Discovery:
- Services register themselves with a service registry (e.g., Spring Cloud Netflix Eureka).
- Service discovery allows services to locate and communicate with each other dynamically.
- API Gateway:
- An API Gateway (e.g., Spring Cloud Gateway, Netflix Zuul) is used to manage and route external requests to the appropriate microservices.
- It can handle authentication, load balancing, and routing.
- Configuration Management:
- Centralised configuration management (e.g., Spring Cloud Config) allows microservices to retrieve configuration properties dynamically.
- Configuration can be stored in a version-controlled repository and updated without redeploying services.
- Distributed Data Management:
- Microservices often have their own databases, and the choice of database depends on the specific requirements of each service.
- Eventual consistency and distributed data management strategies may be employed.
- Events and messaging systems (e.g., Spring Cloud Stream, Apache Kafka) are used for communication between microservices.
- Event-driven architecture supports loose coupling and scalability.
- Polyglot Architecture:
- Each microservice can be implemented in a different programming language or use a different technology stack, known as a polyglot architecture.
- The choice of technology is based on the specific requirements of each service.
- Testing and Continuous Integration/Continuous Deployment (CI/CD):
- Microservices are independently testable, allowing for easier unit testing and integration testing.
- CI/CD pipelines enable automated testing and deployment of microservices.
- Domain-Driven Design (DDD):
- Microservices are often designed based on domain-driven design principles, emphasising a clear understanding of the business domain and its interactions.
This architecture allows for flexibility, scalability, and easy maintenance of a microservices-based system. Spring Cloud provides a set of tools and libraries to implement many of these patterns and streamline the development of microservices in a Spring Boot environment.
Also Read: Spring Boot Tutorial
Controller Layer in Spring Boot
In a Spring Boot application, the controller layer is a crucial component responsible for handling incoming HTTP requests, processing them, and producing appropriate responses. It plays a key role in the Model-View-Controller (MVC) architectural pattern. Below are key aspects and responsibilities of the controller layer in Spring Boot:
- Annotation:
- Controllers are typically annotated with @Controller or @RestController. The @RestController annotation is often used for RESTful APIs and includes the @Controller and @ResponseBody annotations.
- Request Mapping:
- Controllers define methods that handle specific HTTP requests. These methods are annotated with @RequestMapping or more specialised annotations like @GetMapping, @PostMapping, etc.
- Request mappings specify the URI path and HTTP method that the method should respond to.
- Method Parameters:
- Controller methods can have parameters that are automatically populated with data from the HTTP request, such as path variables (@PathVariable), request parameters (@RequestParam), request headers (@RequestHeader), and the request body.
- Response Handling:
- Controller methods return data that will be included in the HTTP response. The return type can be a Java object, which is automatically converted to JSON (or another format) using Spring’s content negotiation.
- For RESTful APIs, the @ResponseBody annotation can be used to indicate that the return value should be serialised directly to the response body.
- View Rendering (for MVC):
- In traditional MVC applications, where server-side rendering is used, the controller may return a logical view name that is resolved by the ViewResolver to an actual view template.
- For RESTful APIs, the focus is on data returned as JSON or XML rather than rendering HTML views.
- Exception Handling:
- Controllers can handle exceptions using @ExceptionHandler methods. These methods define how the application should respond when a specific exception occurs during request processing.
- Validation:
- Controllers may perform input validation by using validation annotations such as @Valid in method parameters. Validation errors can be captured and handled in the controller.
- Interception and Filters:
- Controllers can be intercepted using interceptors (HandlerInterceptor) to perform pre- or post-processing logic.
- Filters (javax.servlet.Filter) can also be applied at the servlet level for more fine-grained request processing.
- Cross-Origin Resource Sharing (CORS) Handling:
- For web applications, controllers can configure CORS settings using annotations like @CrossOrigin to control which domains are allowed to access the resources.
- Controllers often play a role in handling security aspects such as authentication and authorization. Spring Security can be integrated to secure controller methods.
- Controllers are unit-testable. Spring provides testing support through @WebMvcTest for testing the controller layer in isolation.
The controller layer acts as an interface between the external world (HTTP requests) and the application’s business logic (service layer). It helps in maintaining a clear separation of concerns in the application architecture.
What is Spring Boot Architecture?
Spring Boot follows a modular and opinionated architectural pattern that simplifies the development of production-ready, stand-alone Spring-based applications. It builds on the concepts of the broader Spring Framework and provides defaults for convention over configuration, allowing developers to quickly set up and deploy applications.
Here’s an overview of the key components in the architecture of a Spring Boot application:
- Standalone Application:
- Spring Boot applications are designed to be standalone, meaning they are self-contained and can be run with minimum configuration. They don’t require external servlet containers like Tomcat or Jetty, as they embed an embedded server (typically Tomcat, Jetty, or Undertow).
- Opinionated Defaults:
- Spring Boot provides a set of defaults and conventions for configuration, reducing the need for extensive boilerplate code.
- It aims to minimise the effort required for developers to configure and set up the application, making it easier to get started quickly.
- Spring Framework Core:
- At its core, Spring Boot is built on top of the Spring Framework. It inherits the fundamental concepts of Inversion of Control (IoC), Dependency Injection (DI), and Aspect-Oriented Programming (AOP) from the Spring Framework.
What Is the Production Architecture of Spring Boot?
The production architecture of a Spring Boot application typically involves deploying microservices in containerized environments with orchestration (e.g., Kubernetes), load balancing, and service discovery. Cloud-native principles, such as containerization with Docker, API gateways (e.g., Spring Cloud Gateway), security measures (e.g., OAuth), and continuous integration/deployment (CI/CD) pipelines are employed. Monitoring tools (e.g., Spring Boot Actuator), logging (e.g., SLF4J with Logback), and resilience patterns (e.g., circuit breakers) ensure robustness.
The choice of databases, scalability, and adherence to compliance regulations contribute to a production-ready architecture, providing high availability, fault tolerance, and efficient resource utilisation.
Also Read: Spring Boot Rest API: Rest APIS with Java and Spring Boot
What is the Architecture of Spring Boot Repository?
The architecture of a Spring Boot repository typically involves the use of Spring Data JPA or other data access technologies. Repositories, annotated with @Repository, encapsulate data access logic and connect the application’s service layer to the underlying database. Entities represent the data model, annotated with JPA annotations for database mapping.
The Service layer orchestrates business logic and interacts with repositories to perform CRUD operations. Spring Boot’s auto-configuration simplifies repository setup, and custom repositories may extend CrudRepository or JpaRepository. This architecture supports modular, maintainable, and scalable applications with efficient database interactions.
What is 3 tier Architecture in Spring Boot?
The 3-tier architecture in Spring Boot divides an application into three layers: Presentation, Service, and Data Access. The Presentation layer includes controllers handling user interactions, the Service layer encapsulates business logic, and the Data Access layer manages interactions with the database.
Controllers process HTTP requests, invoking service methods that orchestrate business logic. Service classes interact with repositories or DAOs, which, in turn, perform database operations on entities. This modular architecture enhances maintainability, scalability, and separation of concerns, allowing each layer to be developed and tested independently, fostering a clearer organisation of code and facilitating future modifications.
Spring Boot offers a streamlined architecture for building Java applications. Its key features include auto-configuration, embedded servers, and a simplified setup, making it a popular choice for developing robust and production-ready applications with minimal boilerplate code and configuration.
For Latest Tech Related Information, Join Our Official Free Telegram Group : PW Skills Telegram Group
Architecture of Spring Boot FAQs
What is the key component of spring boot architecture.
The core component is the embedded web server that eliminates the need for external servlet containers, making Spring Boot applications standalone and easily deployable.
How does Spring Boot simplify configuration?
Spring Boot simplifies configuration through auto-configuration, providing sensible defaults and reducing the need for extensive manual configuration.
What role does the Spring Boot Actuator play in production?
Spring Boot Actuator provides production-ready features for monitoring and managing applications, including health checks, metrics, and application environment details.
How does Spring Boot support containerization?
Spring Boot applications can be easily containerized using Docker, allowing for consistent deployment across different environments and facilitating cloud-native development.
What is the significance of Spring Boot Starters?
Spring Boot Starters are pre-configured templates that include common dependencies, simplifying dependency management and accelerating the setup of specific functionalities like web applications, data access, and messaging.
- Java Internship at Paarsh Infotech [With Stipend]: Apply By 10 Nov’ 24
Apply for different roles for online Java internship on top websites and career pages of organisations. Join as a remote…
- Java Basics | Basics of Java
Java is a popular programming language used to develop mobile applications, web pages, games and more. Java basics include syntax…
- Top 30 Java Interview Question and Answers
Learn top 30 Java interview question with expertly crafted answers and Prepare for your next Java interview with confidence! Reading…
Related Articles
- Java Course Duration, Syllabus Eligibility, Salary, Fees
- How To Take Input From Users In Java?
- Getting Started With Java Hello World Program
- History Of Java Programming Language A Complete Guide
- Java Full Stack Developer Course
- Java Developer Course
- If Else Statement Java with Examples
- Java Tutorial
- Java Spring
- Spring Interview Questions
- Java SpringBoot
- Spring Boot Interview Questions
- Spring MVC Interview Questions
- Java Hibernate
- Hibernate Interview Questions
- Advance Java Projects
- Java Interview Questions
How Spring Boot Application Works Internally?
Spring Boot Application starts using a main method, like any other Java program, and the main method is called the “ run ” method i.e. SpringApplication.run() ,. From this run method, the application context of IOC (Inversion Of Control) searches the class annotated with @Configuration annotation which calls all the beans in the classpath and initializes those classes. Beans are stored inside a particular space in JVM (Java Virtual Machine) . That particular space is known as the IOC Container .
After beans are created the requests will go to the dispatcher servlet and the dispatcher servlet will distribute all the requests among the appropriate controllers. To understand how a Spring Boot application works internally, it is essential to know its key components and the flow of the application.
Spring Boot Layered Architecture
Spring Boot follows a layered architecture in which each layer communicates with the other layer directly in a hierarchical structure.
If you’re looking to dive deeper into how Spring Boot works internally and want to build high-performance applications, the Java Backend Live Course is a great resource. It covers core concepts like Spring Boot auto-configuration and bean management, helping you build scalable applications. Learn more here .
There are 4 layers in Spring Boot as follows:
- Presentation Layer
- Business Layer
- Persistence Layer
- Database Layer
1. Presentation Layer
This layer handles all the HTTP requests made by clients, then it translates the JSON parameter to object and also authenticates the request, and transfer it to the business layer. In short, it only consists of the frontend part or we can say the view part.
2. Business Layer
This is also known as the Service layer which handles all the business logic of an application. It consists of service classes and uses services provided by the data access layers. It also performs authorization and validation.
3. Persistence Layer
It contains all the storage logic which are required and translates the business objects to database rows.
4. Database Layer
In this layer, all the CRUD (create, read update, delete) operations are performed.
Spring Boot Application Flow Architecture
Let us understand the control flow of a Spring Boot Application in the below diagram:
Explanation:
- Client makes an HTTP request(GET, POST, PUT, DELETE) to the browser.
- Then the request will go to the controller where all the requests will be mapped and handled.
- After mapping done, in Service layer all the business logic will be performed. It performs the logic on the data that is mapped to JPA(Java Persistence API) using model classes.
- In repository layer, all the CRUD operations is done for the rest APIs.
- A JSP page is returned to the user if no errors are there.
How Does Spring Boot Application Starts?
Spring Boot is very popular for It’s auto-configuration feature. This means it automatically configures our application based on the dependencies added during the project creation. As we don’t need to configure xml file, Spring internally do all the xml configuration which are provided by jar. We just have to use the pre-configured jars. To enable those pre-configured jars, simply we need to define starter dependencies in pom.xml file.
By adding this starter-data-jpa dependency , we get all the pre-configured JPA configuration which are needed for connecting our application with the database. Then we just need to focus on defining the JPA entities, repositories, business logic, while Spring Boot takes care of all internal configuration and database interaction.
Basic Annotations to Start a Spring Boot Application
The entry point of the Spring Boot Application is the class which contains @SpringBootApplication annotation along with the main method. The main method should contain SpringApplication.run method.
Below is the implementation of the above method:
Here we have used @SpringBootApplication annotation along with the class GFG and a main method just like other java program with SpringApplication.run method to bootstrap the application.
How @SpringBootApplication Works?
@SpringBootApplication annotation is the combination of another three annotations i.e. @Configuration , @EnableAutoConfiguration, @ComponentScan .
@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan
@Configuration A nnotation:
- This annotation configures the application context such as transaction, resource handler, view resolver, security etc.
- It is used in class level and it specifically indicates that a class declare one or more than one @Bean methods.
@EnableAutoConfiguration A nnotation:
- This annotation will automatically configures our application we don’t need to configure manually.
- It enables the auto-configuration feature of Spring Boot.
Here we have used @EnableAutoConfiguration annotation along with the class name to perform the automatic configuration over an application.
@ComponentScan A nnotation:
- This annotation will automatically scans all the beans and package declaration when the application initializes inside the class path.
- It will automatically scan all the components added to our project.
Here we have used @ComponentScan annotation along with the @SpringBootApplication annotation which will scan the package which is passed inside the parameter. We can also use this annotation without argument, where Spring is responsible for scan the current package and it’s sub-packages. We can use these annotations separately as per our need because spring boot supports loosely coupled feature.
Spring Boot enables the developers to use a single annotation instead of using three different annotations we can use one annotation which has the default attributes of all those annotations.
Spring Boot is an open-source framework of java built on the top of the Core Spring framework. Here we learnt about different layers of Spring Boot architecture. We also learnt about project flow of Spring Boot application, different annotations to start the RESTful web application.
Similar Reads
- Advance Java
- Java-Spring-Boot