0% found this document useful (0 votes)
2 views14 pages

Day25 Spring Boot

Spring Boot is an open-source Java framework that simplifies application development by reducing configuration needs and supporting embedded servers. It enhances productivity through features like auto-configuration, starter dependencies, and seamless integration with other Spring tools. The document also outlines the setup process for a Spring Boot project, including creating REST endpoints and customizing configurations.

Uploaded by

21512316.dypit
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

Day25 Spring Boot

Spring Boot is an open-source Java framework that simplifies application development by reducing configuration needs and supporting embedded servers. It enhances productivity through features like auto-configuration, starter dependencies, and seamless integration with other Spring tools. The document also outlines the setup process for a Spring Boot project, including creating REST endpoints and customizing configurations.

Uploaded by

21512316.dypit
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduc on to Spring Boot

What is Spring Boot?


Spring Boot is an open-source Java-based framework that simplifies the development of produc on-ready applica ons.
It is built on the Spring Framework and eliminates the need for extensive configura on, allowing developers to focus
on building features rather than dealing with complex setup processes. The core philosophy of Spring Boot is
conven on over configura on, meaning it provides sensible defaults and configura ons that work out-of-the-box for
most applica ons.

Key Highlights:

 Provides a simplified way to develop applica ons with minimal configura on.

 Supports embedded servers (e.g., Tomcat), enabling applica ons to run independently without the need for
external containers.

 Encourages fast, efficient, and scalable applica on development.

Why Use Spring Boot?


Spring Boot solves common challenges faced by developers when working with tradi onal Spring applica ons, such as
extensive XML configura on and dependency management issues. Here’s why Spring Boot is so widely adopted:

 Rapid Development: Offers default configura ons and pre-built components that help developers build
applica ons quickly.

 Embedded Servers: Includes embedded servers like Tomcat and Je y, making deployment easier.

 Ease of Integra on: Works seamlessly with other Spring tools, microservices architectures, and cloud
environments.

 Auto-Configura on: Automa cally detects and configures beans based on your project structure.

Differences Between Spring and Spring Boot


Understanding the dis nc on between Spring and Spring Boot helps clarify the advantages Spring Boot offers.

Aspect Spring Framework Spring Boot

Configura on Extensive manual configura on required Auto-configura on out-of-the-box

Dependency Manual dependency resolu on Starter dependencies for streamlined


Management management

Deployment Requires external servers Embedded servers (e.g., Tomcat, Je y)

Purpose General-purpose framework for enterprise Specialized framework for rapid applica on
applica ons development

Spring Boot streamlines the Spring development process, providing a more developer-friendly experience.

Features and Advantages of Spring Boot


Features:

1. Starter Dependencies: Simplifies dependency management by grouping dependencies into starter packs (e.g.,
spring-boot-starter-web).
Compiled By: Rohit Ahuja (9893075987) h ps://[Link]/@vediso _in
2. Auto-Configura on: Automa cally configures your applica on based on project requirements, reducing
manual setup.

3. Embedded Servers: Allows applica ons to run independently with embedded servers (e.g., Tomcat).

4. Actuator: Provides built-in tools to monitor and manage applica on metrics, such as health checks and system
insights.

Advantages:

 Reduces boilerplate code and development me.

 Simplifies applica on tes ng with embedded servers.

 Supports microservices architecture effortlessly.

 Provides excellent integra on with modern DevOps tools.

Understanding Spring Boot vs Spring Framework


Spring Framework is the founda on, offering fundamental capabili es such as dependency injec on, aspect-oriented
programming, and transac on management. Spring Boot builds on this founda on by:

 Automa ng repe ve tasks like configura on and dependency resolu on.

 Enhancing produc vity with embedded servers and starter packs.

 Promo ng modularity and scalability, making it ideal for microservices and cloud-based environments.

Essen ally, Spring Boot complements the Spring Framework, making it easier to work with.

Se ng up a Simple Spring Boot Project


Step 1: Install the Development Environment

Ensure students have installed an IDE, such as IntelliJ IDEA or Eclipse, and have Java Development Kit (JDK) installed.

Step 2: Generate a Spring Boot Project

1. Visit Spring Ini alizr.

2. Choose project details:

o Project: Maven

o Language: Java

o Dependencies: Spring Web

3. Download the generated .zip file.

Step 3: Import the Project into an IDE

1. Extract the downloaded file.

2. Open the IDE and import the project as a Maven project.

Step 4: Write a Simple Applica on

Create a Controller class with a basic Hello World endpoint:


Compiled By: Rohit Ahuja (9893075987) h ps://[Link]/@vediso _in
@RestController

public class HelloController {

@GetMapping("/hello")

public String hello() {

return "{\"message\": \"Hello, World!\"}";

Step 5: Run the Applica on

Start the applica on using the IDE or by execu ng mvn spring-boot:run. Access h p://localhost:8080/hello in your
browser to see the output.

Spring Boot REST API Assignment


Objec ve:

Develop a simple Spring Boot applica on that exposes three REST endpoints:

 /name → returns the user's name

 /address → returns the user's address

 /phone → returns the user's mobile phone number

Requirements:

1. Use Spring Boot to build the applica on.

2. Implement a controller that handles these three endpoints.

3. The endpoints should return hardcoded values for demonstra on purposes.

4. Ensure the responses are in JSON format.

Instruc ons:

1. Setup Project:

o Create a new Spring Boot project using Spring Ini alizr or manually.

o Add dependencies for Spring Web.

2. Create Controller:

o Define a controller class named UserController.

o Implement three methods to handle the requests for /name, /address, and /phone.

3. Return JSON Responses:

o Use @RestController and @GetMapping annota ons.

o Ensure each method returns a proper JSON response.

Compiled By: Rohit Ahuja (9893075987) h ps://[Link]/@vediso _in


Se ng Up Spring Boot Environment
Installing and Configuring Spring Boot
 Install Java Development Kit (JDK): Ensure students have the JDK installed on their machines. Highlight the
importance of Java version compa bility with Spring Boot.

 Install an Integrated Development Environment (IDE): Recommend popular IDEs like IntelliJ IDEA or Eclipse
for Java development.

 Set Up Maven or Gradle: Explain the role of build tools for dependency management and project structuring.
Focus on Maven for simplicity.

 Verify Installa on: Provide students with simple commands to verify Java, Maven, or Gradle installa on (e.g.,
java -version or mvn -version).

Using Spring Ini alizr


Spring Ini alizr is a fantas c tool for kick-star ng Spring Boot projects.

Using the Web Interface:

1. Open Spring Ini alizr.

2. Choose the project type (Maven or Gradle) and language (Java).

3. Select the Spring Boot version and dependencies (e.g., Spring Web, Spring Boot Starter).

4. Generate the project and download the .zip file.

Exploring [Link] Dependencies


The [Link] file is the cornerstone of Maven-based projects, handling dependencies and project se ngs.

Key Elements of [Link]:

1. Project Metadata: Includes ar fact ID, group ID, and version.

2. Dependencies Sec on: Contains libraries needed for the project. Highlight the usage of starter dependencies
(e.g., spring-boot-starter-web).

3. Plugins Sec on: Enable Maven plugins for func onali es like building, tes ng, and deploying.

<dependency>
<groupId>[Link]</groupId>
<ar factId>spring-boot-starter-web</ar factId>
</dependency>

Understanding applica [Link] es and applica [Link]


Spring Boot simplifies configura on using these files.

applica [Link] es:

 A simple key-value format.

Compiled By: Rohit Ahuja (9893075987) h ps://[Link]/@vediso _in


 Used for basic configura ons like server port, database connec on, and logging levels. Example:

[Link]=8080
[Link]=jdbc:mysql://localhost:3306/mydb
[Link]=root
[Link]=root

applica [Link]:

 A hierarchical structure for more complex configura ons. Example:

server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: root

Compiled By: Rohit Ahuja (9893075987) h ps://[Link]/@vediso _in


Spring Boot Auto-Configura on & Starter Dependencies
1. What is Auto-Configura on in Spring Boot?
Spring Boot’s auto-configura on feature automa cally configures your applica on based on the dependencies you
have included in your project. It eliminates the need for manual configura on, making development faster and easier.

Key Highlights:

 Uses @EnableAutoConfigura on to scan the classpath and provide configura ons.

 Selects default beans and se ngs based on the dependencies and environment.

 Provides sensible defaults that work for most applica ons, while s ll allowing customiza on.

Example: If you include spring-boot-starter-data-jpa in your project, Spring Boot will auto-configure a DataSource bean
and Hibernate se ngs.

How Spring Boot Reduces Boilerplate Code


Spring Boot reduces repe ve coding tasks through:

 Auto-Configura on: Automa cally configuring beans for common scenarios, such as web applica ons or database
connec ons.

 Starter Dependencies: Pre-packaged dependencies that simplify project setup.

 Embedded Servers: Eliminates the need for se ng up external server environments (e.g., Tomcat).

 Minimal XML Configura on: Replaces tradi onal Spring XML configura ons with annota ons and proper es files.

This streamlined approach enhances developer produc vity and allows focus on business logic.

Spring Boot Starter Dependencies


Spring Boot provides "starter" dependencies, which are pre-configured sets of dependencies tailored for specific
func onali es.

Common Starter Dependencies:

1. spring-boot-starter-web:

o Designed for building web applica ons.

o Includes libraries like Spring MVC, embedded Tomcat, and Jackson for JSON processing.

2. spring-boot-starter-data-jpa:

o Used for integra ng JPA (Java Persistence API) with Hibernate.

o Simplifies database opera ons with Spring Data.

3. spring-boot-starter-security:

o Provides authen ca on and authoriza on features.

o Includes dependencies for securing web applica ons.

Compiled By: Rohit Ahuja (9893075987) h ps://[Link]/@vediso _in


4. spring-boot-starter-thymeleaf:

o Provides thymelead template engine.

o Includes dependencies for MVC based web applica ons.

5. spring-boot-starter-test:

o Provides tes ng func onality to Spring Boot applica ons.

o Includes dependencies for JUnit, Mockito, Spring Test

These starters eliminate the need to manually manage individual library versions.

Customizing Auto-Configura on
Some mes, the default configura on provided by Spring Boot may not fully meet applica on requirements. Here’s
how to customize auto-configura on:

 Exclude Auto-Configura on Classes: Use the @SpringBootApplica on annota on to exclude specific classes:

 @SpringBootApplica on(exclude = DataSourceAutoConfigura [Link])

 Override Beans: Create custom beans using the @Bean annota on to replace default configura ons.

 Modify applica [Link] es or applica [Link]: Adjust se ngs, like changing the server port or customizing
database configura ons.

Customiza on ensures flexibility without compromising the benefits of auto-configura on.

Exploring and Customizing Auto-Configura on


Spring Boot provides tools to explore and tweak its auto-configura on:

 Enable Debugging for Auto-Configura on: Add debug=true in applica [Link] es to view auto-configured
components.

 Spring Boot Actuator: Use endpoints like /actuator/beans to list all beans and their configura ons.

 Spring Boot Developer Tools: Inves gate how configura ons are applied during development.

Example: Customizing Security Auto-Configura on

If using spring-boot-starter-security, you can override the default login page by defining your own SecurityConfig:

@Configura on
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(H pSecurity h p) throws Excep on {
h p
.authorizeRequests()
.anyRequest().authen cated()
.and()
.formLogin().loginPage("/custom-login").permitAll();
}
}
These steps enable developers to tailor Spring Boot to meet specific applica on needs.

Compiled By: Rohit Ahuja (9893075987) h ps://[Link]/@vediso _in


Spring Boot MVC Architecture
What is Spring MVC?
Spring MVC is a part of the Spring Framework, designed for building web applica ons following the Model-View-
Controller (MVC) architecture. It separates the applica on’s concerns—data handling, user interface, and business
logic—into three dis nct components.

Key Features:

 Built-in support for handling HTTP requests and responses.

 Integra on with various view technologies (e.g., Thymeleaf, JSP).

 Flexible and extensible architecture.

Spring MVC works seamlessly within Spring Boot, offering auto-configura on and embedded server support.

Overview of MVC (Model-View-Controller) Architecture


MVC is an architectural pa ern that divides applica on logic into three components:

1. Model: Represents the data or the business logic of the applica on. It interacts with the database and holds
data that the controller can process.

2. View: Responsible for displaying data to the user. Commonly includes web pages or templates.

3. Controller: Handles user input, processes data from the model, and selects the appropriate view.

Example Flow:

 A user interacts with the view (e.g., submits a form).

 The controller handles the user’s request and interacts with the model.

 The model processes the data and sends it back to the controller.

 The controller forwards the data to the view for rendering.

Request Flow in Spring Boot MVC


Spring Boot MVC follows a defined request flow:

1. User Interac on: The user sends a request via a URL.

2. DispatcherServlet: The request is routed to the DispatcherServlet, which acts as the central controller.

3. Handler Mapping: Maps the request to the appropriate controller method.

4. Controller Processing: The controller processes the request, o en interac ng with services and repositories.

5. View Resolver: Resolves the view (e.g., Thymeleaf template) to render the response.

6. Response: The view is displayed back to the user.

Understanding DispatcherServlet
The DispatcherServlet is the heart of Spring MVC, managing incoming HTTP requests and dispatching them to the
appropriate handler components.

Key Responsibili es:

Compiled By: Rohit Ahuja (9893075987) h ps://[Link]/@vediso _in


 Receives all HTTP requests from clients.

 Delegates processing to handler mappings, controllers, and view resolvers.

 Simplifies request flow by centralizing control.

By default, Spring Boot automa cally registers DispatcherServlet, elimina ng the need for manual configura on.

Controllers, Services, and Repositories in Spring Boot


Spring Boot organizes applica on logic into dis nct layers:

1. Controller Layer: Handles HTTP requests and prepares data for views. Example:

@RestController
public class UserController {
@GetMapping("/users")
public List getAllUsers() {
return userService.findAllUsers();
}
}

2. Service Layer: Contains business logic and processes data before interac ng with repositories. Example:

@Service
public class UserService {
@Autowired
private UserRepository userRepository;

public List<User> findAllUsers() {


return userRepository.findAll();
}
}
3. Repository Layer: Interacts directly with the database using JPA or other persistence methods. Example:

@Repository public interface UserRepository extends JpaRepository {}

This layered architecture ensures clean separa on of concerns and improves maintainability.

Implemen ng a Simple Spring Boot MVC Applica on


Create a Spring Boot applica on where a user sends a request to the server and receives a simple "Hello, MVC!"
message.

Steps to Build the Applica on

1. Set up the Project

 Go to Spring Ini alizr.

 Configure the following:

o Project: Maven

o Language: Java

o Spring Boot Version: Choose the latest stable version.

Compiled By: Rohit Ahuja (9893075987) h ps://[Link]/@vediso _in


o Dependencies: Add Spring Web, Thymeleaf.

 Click Generate and download the project. Extract the .zip file and open it in an IDE like IntelliJ IDEA or Eclipse.

2. Write a Controller

The Controller will handle HTTP requests and return the response.

 Create a new Java class HelloController under src/main/java/com/example/demo (or your package name).

 Add the following code:

package [Link];

import [Link];
import [Link] [Link];
import [Link];

@Controller
public class HelloController {

@GetMapping("/hello")
public String hello(Model model) {
[Link] ribute("message", "Hello, MVC!");
return "hello"; // Refers to the '[Link]' view
}
}

3. Create the View

The View will display the data sent by the Controller.

 Create a new folder templates inside src/main/resources.

 Inside the templates folder, create an HTML file named [Link].

 Add the following code:

<!DOCTYPE html>
<html xmlns:th="h p://[Link]">
<head>
< tle>Hello MVC</ tle>
</head>
<body>
<h1>Spring Boot MVC Example</h1>
<p>Message: <span th:text="${message}"></span></p>
</body>
</html>

4. Run the Applica on

 Navigate to the DemoApplica on class (or the class annotated with @SpringBootApplica on in your project).

 Run the applica on by clicking the "Run" bu on in your IDE or using the terminal command:

 mvn spring-boot:run

Compiled By: Rohit Ahuja (9893075987) h ps://[Link]/@vediso _in


5. Access the Applica on

 Open your browser and go to h p://localhost:8080/hello.

 You should see the message "Hello, MVC!" displayed on the webpage.

This is a minimal and straigh orward example of a Spring Boot MVC applica on. It demonstrates the key parts of the
architecture: Controller (handling requests), Model (passing data), and View (displaying results).

Spring Boot MVC Assignment


Objec ve:

Develop a simple Spring Boot applica on that exposes three endpoints:

 /name → this adds the user's name to model

 /address → this adds the user's address to model

 /phone → this adds the user's mobile phone number to model

Requirements:

1. Use Spring Boot to build the applica on.

2. Implement a controller that handles these three endpoints.

3. The endpoints should return the view (html file).

4. Ensure the responses are in String format.

Instruc ons:

1. Setup Project:

o Create a new Spring Boot project using Spring Ini alizr or manually.

o Add dependencies for Spring Web.

2. Create Controller:

o Define a controller class named UserController.

o Implement three methods to handle the requests for /name, /address, and /phone.

3. Return String Responses:

o Use @Controller and @GetMapping annota ons.

o Ensure each method returns a proper String response (HTML File).

4. Html Fles:

o Create html file for each string response.

o This html file should display corresponding name, address or mobile.

Compiled By: Rohit Ahuja (9893075987) h ps://[Link]/@vediso _in


Difference between @Controller and @RestController
@Controller
 Used for tradi onal MVC applica ons where the response is typically an HTML view.

 Works with View Resolvers like Thymeleaf or JSP.

 Returns a view name rather than actual data.

 Example:

@Controller
public class HomeController {
@GetMapping("/home")
public String home() {
return "home"; // Returns "[Link]" or "[Link]" view
}
}

 Ideal for web applica ons with UI templates.

@RestController
 A combina on of @Controller + @ResponseBody.

 Used for REST APIs, where the response is typically JSON or XML.

 Automa cally serializes Java objects into JSON.

 Example:

@RestController
public class ApiController {
@GetMapping("/hello")
public String hello() {
return "{\"message\": \"Hello, World!\"}";
}
}
 Ideal for RESTful web services.

Which One Should You Use?


 If you're building a web applica on with views → Use @Controller.

 If you're building a REST API → Use @RestController.

Compiled By: Rohit Ahuja (9893075987) h ps://[Link]/@vediso _in


@SpringBootApplica on
It is a combina on of three annota ons:

1. @SpringBootConfigura on – Marks the class as a configura on file (like @Configura on).

2. @EnableAutoConfigura on – Automa cally configures Spring components based on dependencies.

3. @ComponentScan – Scans for components (@Controller, @Service, @Repository, etc.) in the package and its
sub-packages.

How to Use It?


In a Spring Boot applica on, it is typically placed on the main class:

import [Link] on;


import [Link]fi[Link] on;

@SpringBootApplica on
public class MyApp {
public sta c void main(String[] args) {
SpringApplica [Link]([Link], args);
}
}

Why is It Important?
 Simplifies configura on – Eliminates the need for XML or mul ple annota ons.
 Auto-configures beans – Detects dependencies like Spring MVC or Spring Data and configures them
automa cally.
 Enables component scanning – Finds all Spring components without extra setup.

@SpringBootApplica on makes Spring Boot applica ons easy to set up, manage, and scale, reducing boilerplate code
while ensuring best prac ces.

Compiled By: Rohit Ahuja (9893075987) h ps://[Link]/@vediso _in


Flow of a Spring Boot applica on
The flow of a Spring Boot applica on follows a well-structured process that enables easy development, deployment,
and execu on. Here’s a step-by-step breakdown:

1. Applica on Startup

 The applica on begins execu on when the main method runs inside a class annotated with
@SpringBootApplica on.

 Spring Boot Ini aliza on happens via:

 SpringApplica [Link]([Link], args);

 This bootstraps the Spring framework, auto-configures dependencies, and prepares the applica on context.

2. Auto-Configura on & Component Scanning

 Auto-Configura on: Spring Boot automa cally configures beans based on dependencies in the [Link] or
[Link].

 Component Scanning: It scans for @Controller, @Service, and @Repository annota ons in the package
hierarchy.

3. Request Handling via Dispatcher Servlet

 Spring MVC’s Dispatcher Servlet receives HTTP requests and routes them based on mappings defined in
@Controller or @RestController.

 Example of a request flow:

 User requests → DispatcherServlet → Controller → Service → Repository → Database → Response back to


User

4. Controller Layer

 A controller handles incoming HTTP requests, processes them, and sends responses.

 Example:

@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/hello")
public String hello() {
return "{\"message\": \"Hello, World!\"}";
}
}
 The request /api/hello returns JSON data.

Final Flow Summary

Start Applica on → Auto-Configura on → Component Scanning → DispatcherServlet → Controller → Service →


Repository → Database → Response to User

This streamlined architecture makes Spring Boot applica ons scalable, efficient, and easy to develop.

Compiled By: Rohit Ahuja (9893075987) h ps://[Link]/@vediso _in

You might also like