KEMBAR78
Spring Boot Notes | PDF | Spring Framework | Databases
0% found this document useful (0 votes)
153 views23 pages

Spring Boot Notes

Chapter 4 introduces the Spring Framework and Spring Boot, highlighting Spring's role as an open-source Java platform that simplifies application development through features like Dependency Injection and Aspect-Oriented Programming. It discusses Spring Boot as a framework for creating microservices with minimal configuration, emphasizing its advantages such as embedded servers and reduced boilerplate code. The chapter also outlines the architecture of Spring Boot applications, the setup process in Spring Tool Suite, and the use of Spring Boot starters for dependency management.
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)
153 views23 pages

Spring Boot Notes

Chapter 4 introduces the Spring Framework and Spring Boot, highlighting Spring's role as an open-source Java platform that simplifies application development through features like Dependency Injection and Aspect-Oriented Programming. It discusses Spring Boot as a framework for creating microservices with minimal configuration, emphasizing its advantages such as embedded servers and reduced boilerplate code. The chapter also outlines the architecture of Spring Boot applications, the setup process in Spring Tool Suite, and the use of Spring Boot starters for dependency management.
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
You are on page 1/ 23

CHAPTER – 4

INTRODUCTION TO SPRINGFRAMEWORK AND SPRINGBOOT

Overview of Spring Framework

What is Spring Framework?


• Spring framework is an open source Java platform that provides
comprehensive infrastructure support for developing robust Java applications very
easily and very rapidly.
• Spring framework was initially written by Rod Johnson and was first
released under the Apache 2.0 license in June 2003
• Based on Dependency Injection (DI) and Aspect-Oriented Programming
(AOP).
• It provides support to many other frameworks such as Hibernate, Tapestry,
EJB, JSF, Struts, etc. so it is also called a framework of frameworks.
• It’s an application framework and IOC (Inversion of Control) container for
the Java platform. The spring contains several modules like IOC, AOP, DAO,
Context, WEB MVC,

Features of springframework
1. Dependency Injection (DI) & Inversion of Control (IoC)
• Spring's IoC container manages object creation and dependencies,
promoting loose coupling and making it easier to modify, test, and maintain code.
Dependencies are injected by Spring—not manually hardcoded—using
constructor, setter, or field injection.
2. Aspect-Oriented Programming (AOP)
• AOP lets you separate cross-cutting concerns (like logging, security, and
transaction management) from business logic, making the codebase cleaner and
more modular. Developers define "aspects" that apply to multiple classes without
duplicating code.
3. Modular Architecture
• Spring is divided into modules (Core, Beans, Context, AOP, Data Access,
Web, etc.), allowing developers to use only what they need. This keeps
applications lightweight and adaptable.
4. Data Access and Integration
• Spring simplifies database access via modules for JDBC, ORM (Hibernate,
JPA), and transaction management. It provides consistent APIs and exception
handling, reducing boilerplate and making integration with relational and NoSQL
databases easier.
5. Spring MVC (Web Development)
• The Spring MVC module is a robust framework for building web applications
using the Model-View-Controller architectural style. It offers features like request
mapping, view resolution, data binding, validation, and easy integration with
RESTful APIs.
6. Transaction Management
• Spring provides a flexible, declarative, and consistent abstraction for
transaction management across various resources, including databases and
message queues. It supports both programmatic and declarative approaches using
annotations or XML.
7. Security
• With the Spring Security subproject, the framework offers comprehensive
authentication, authorization, and security policy enforcement for enterprise
applications, seamlessly protecting web and RESTful endpoints.
8. Testing Support
• Spring supports unit and integration testing by allowing easy injection of
mocks or stubs, facilitating robust test-driven development.
9. Integration With Other Technologies
• Out-of-the-box support for integration with technologies like Hibernate,
JMS, JPA, and even legacy systems, making it versatile for various enterprise
demands.
10. Internationalization (i18n) and Validation
• The framework supports internationalization and localization of user-facing
messages, as well as unified validation mechanisms for user input.

Spring Boot
• Spring Boot is an open source Java-based framework used to create a Micro
Service.
• It is developed by Pivotal Team.
• It is easy to create a stand-alone and production ready spring applications
using Spring Boot.
• Spring Boot contains a comprehensive infrastructure support for developing
a micro service and enables you to develop enterprise-ready applications that you
can just run

Spring Boot Key Features

1. Web Development
Spring Boot streamlines web development by providing embedded Tomcat, Jetty,
or Undertow servers. This eliminates the need for external deployment and allows
you to create stand-alone, production-ready web applications with minimal
configuration. It supports RESTful APIs, MVC architecture, and traditional web
applications out of the box.
2. Spring Application
Spring Boot applications are standalone and easy to run. You can package your
application as an executable JAR (with an embedded server) and start it with a
simple command. It offers production-ready features like health checks and
metrics, and simplifies the Spring application lifecycle by automatically configuring
most components.
3. Application Events and Listeners
Spring Boot extends Spring’s event-driven model. You can publish custom or built-
in application events, and create listeners to handle specific actions (such as
contexts starting/stopping or custom business events), promoting loose coupling
between components and simplifying cross-module communication.
4. Admin Features
Spring Boot Admin is a community project that allows you to manage and monitor
your Spring Boot applications. Features include real-time health checks, log
management, environment and metrics visualization, notifications, and even
runtime updating of log levels. It provides a user-friendly dashboard and supports
secure monitoring.
5. Externalized Configuration
With Spring Boot, you can externalize your configuration using properties files,
YAML files, environment variables, or command-line arguments. This separates
configuration data from code, making it easy to adapt the application to different
environments and manage sensitive information securely.
6. Properties Files
Properties files (usually application.properties) are the most common way to
provide configuration in Spring Boot. These files allow you to configure everything
from server ports to database URLs and custom app settings. They support profile-
specific configurations for environments like dev, test, and prod.
7. YAML Support
Spring Boot supports YAML as an alternative to properties files. YAML’s
hierarchical structure makes it suitable for representing complex configurations in
a readable way (e.g., nested objects or lists). Spring Boot automatically
loads application.yml if present.
8. Type-safe Configuration
Spring Boot provides type-safe configuration by binding externalized properties
directly to Java objects using the @ConfigurationProperties annotation. This
ensures configuration values are validated at startup and accessed using strongly-
typed fields, reducing runtime errors and simplifying refactoring.
9. Logging
Logging is fully integrated in Spring Boot with sensible defaults using Logback, but
you can easily switch to Log4j2 or other logging systems. Spring Boot creates
application logs for errors, warnings, and custom events, and lets you control log
levels via configuration. You can also route logs to files, consoles, or remote
servers out of the box.
10. Security
Spring Boot integrates seamlessly with Spring Security to provide authentication,
authorization, and secure communication. Out-of-the-box features include
password encoding, customizable login forms, OAuth2 integration, and role-based
access controls. You can secure endpoints, define user roles, and add custom
security filters using straightforward configuration properties

Spring Boot Advantages


• It generates standalone Spring applications that are launched with the Java
-jar command.
• It easily tests web applications using several Embedded HTTP servers like as
Tomcat, Jetty, and others. We don't need to distribute WAR files.
• It provides 'starter' POMs with strong opinions to help us simplify our
Maven settings.
• It includes features that are ready for production, such as metrics, health
checks, and externalised settings.
• There is no need for XML configuration.
• It includes a command-line utility for designing and testing Spring Boot
applications.
• It provides a number of plug-ins.
• It also minimizes writing multiple boilerplate codes, XML configuration, and
annotations.
• It boosts productivity while decreasing development time.

Limitations of Spring Boot


• It can be tricky to learn at first, especially for beginners.
• It may use more memory and take longer to start compared to simpler
frameworks.
• Its conventions can restrict customization options for specific needs.
• Managing multiple microservices can get complicated.
• Upgrading or integrating with certain tools may be tricky.
• Applications built with Spring Boot can be larger to deploy.

Spring Boot vs Spring Framework

Spring Spring Boot

Spring Boot is built on top of the conventional


Spring is an open-source lightweight framework
spring framework, widely used to develop REST
widely used to develop enterprise applications.
APIs.

The most important feature of the Spring The most important feature of the Spring Boot is
Framework is dependency injection. Autoconfiguration.

It helps to create a loosely coupled application. It helps to create a stand-alone application.

To run the Spring application, we need to set the Spring Boot provides embedded servers such as
server explicitly. Tomcat and Jetty etc.

To run the Spring application, a deployment There is no requirement for a deployment


descriptor is required. descriptor.

To create a Spring application, the developers


It reduces the lines of code.
write lots of code.

It doesn't provide support for the in-memory It provides support for the in-memory database
database. such as H2.
Spring Spring Boot

Developers need to write boilerplate code for In Spring Boot, there is reduction in boilerplate
smaller tasks. code.

Developers have to define dependencies pom.xml file internally handles the required
manually in the pom.xml file. dependencies.

Spring Boot - Architecture


Spring Boot is built on top of the core Spring framework. It simplifies and
automates Spring-based application development by reducing the need for
manual configuration. Spring Boot follows a layered architecture, where each
layer interacts with other layers in a hierarchical order. The official Spring Boot
documentation defines it as:
Spring Boot Layers
Spring Boot consists of the following four layers:
1. Presentation Layer: Handles HTTP requests, authentication, and JSON
conversion.
2. Business Layer: Contains business logic, validation, and authorization.
3. Persistence Layer: Manages database interactions using ORM frameworks
like Spring Data JPA.
4. Database Layer: Stores application data using relational (MySQL,
PostgreSQL) and NoSQL databases (MongoDB, DynamoDB).
1. Presentation Layer
The Presentation Layer is the topmost layer of the Spring Boot architecture. It
primarily consists of REST controllers that handle HTTP requests (GET, POST, PUT,
DELETE). It performs authentication, request validation, and JSON
serialization/deserialization (conversion of JSON to Java objects and vice versa).
After processing the request, it forwards the request to the business layer.
2. Business Layer
The Business Layer is responsible for implementing the application's core logic. It
consists of service classes that:
• Process and validate data.
• Handle authentication and authorization (integrating Spring Security if
needed).
• Apply transaction management using @Transactional.
• Interact with the Persistence Layer to store or retrieve data.
3. Persistence Layer
The Persistence Layer manages database transactions and storage logic. It consists
of repository classes using Spring Data JPA, Hibernate, or R2DBC for data access. It
is responsible for:
• Mapping Java objects to database records using ORM frameworks.
• Managing CRUD (Create, Read, Update, Delete) operations.
• Supporting relational and NoSQL databases.
4. Database Layer
The Database Layer contains the actual database where the application data is
stored. It can support:
• Relational Databases (MySQL, PostgreSQL, Oracle, SQL Server).
• NoSQL Databases (MongoDB, Cassandra, DynamoDB, Firebase).
• Cloud-based databases for scalability.
Explanation:
• The client (frontend or API consumer) sends an HTTP request (GET, POST,
PUT, DELETE) to the application.
• The request is handled by the Controller Layer, which maps the request to a
specific handler method.
• The Service Layer processes business logic and communicates with the
Persistence Layer to fetch or modify data.
• The Persistence Layer interacts with the Database Layer using Spring Data
JPA or R2DBC, often through a Repository Class that extends CRUD services.
• The processed response is returned as JSON.
• Spring Boot Actuator can be used for monitoring and health checks.

How to Create and Setup Spring Boot Project in Spring Tool Suite?
Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise
applications. It is easier, faster, and more convenient. And most importantly it is
based on Eclipse IDE. STS is free, open-source, and powered by VMware.
Procedure:
1. Install Spring Tool Suite IDE
2. Create a new Spring project
3. Fill details in the pop-up window and press Next.
4. Choose Spring Boot version and select dependencies and press Next.
5. Click on the 'Finish' button.
Step 1: Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE
For this user must have pre-requisite knowledge of downloading and installing
Spring Tool Suite IDE
Step 2: Go to the File > New > Spring Starter Project
Step 3: In this pop-up window fill the detail below as follows and further click on
the Next button as shown in the below image.
• Service URL: Default
• Name: Your Project Name
• Type: Maven Project
• Java Version: 11 or greater than 11
• Packaging: As your need
• Language: As your need
• Group: A unique base name of the company or group that created the
project
• Artifact: A unique name of the project
• Version: Default
• Description: As your need
• Package: Your package name
Step 4: Choose your required Spring Boot Version and select your dependencies
as per your project requirement. And at last click on the Next button.
Step 5: Now simply click on the Finish button.
Here now, please wait for some time to download all the required files such as
dependencies that you have selected in Step4 above.
Welcome screen after you have successfully Created and Setup Spring Boot Project
in Spring Tool Suite

How to Run Your First Spring Boot Application in Spring Tool Suite?
Spring Tool Suite (STS) is a Java IDE tailored for developing Spring-based
enterprise applications. It is easier, faster, and more convenient. Most importantly,
it is based on Eclipse IDE. STS is free, open-source, and powered by VMware.
Procedure
1. Create a Spring Boot project in Spring Tool Suite
2. Import the Project into STS IDE
3. An entry file named Application.java will be created for STS
4. Run the application on the server.
Step 1: Create Spring Boot Project in Spring Tool Suite
create your first Spring Boot Application. Alternatively, you can use Spring
Initializr to create your project and then import it into your STS IDE.
Step 2: Import the Project into Your STS IDE
2.1: Open the Project in STS
Go to your STS IDE > File > Open Project from File System
2.2: Select Your Project Directory
A pop-up window will occur like the following. Here you have to choose the
directory that has been generated while creating the spring boot project in Spring
Initializr. And then click on the Finish button.
Step 3: Application.java
After successfully creating or importing the spring boot project a file name
Application.java (here, DemoApplication) will be created automatically and this is
your entry point. This file serves as the main method of your Spring Boot
application.
Step 4: Run the Spring Boot Application
4.1: Run the Application in STS
In order to run this application now, Right-click on the DemoApplication.java >
Run As > Spring Boot App as shown in the below image.
4.2: Console Output:
After successfully running the application you can see the console where the
Tomcat server starts on default port number 8080 as shown in the below image.

Spring Boot - Starters


Spring Boot Starters are dependency descriptors that can be added under the
<dependencies> section in pom.xml. There are around 50+ Spring Boot Starters
for different Spring and related technologies. These starters give all the
dependencies under a single name.
For example, if you want to use Spring Data JPA for database access, you can
include the spring-boot-starter-data-jpa dependency.
Spring Boot Starter Data JPA is illustrated below:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
THERE ARE 3 SPRINGBOOT STARTERS :

1. Spring Boot Application Starters


Name Description

Core starter, including auto-configuration support,


spring-boot-starter
logging, and YAML

pring-boot-starter-data-jdbc Starter for using Spring Data JDBC

spring-boot-starter-data-jpa Starter for using Spring Data JPA with Hibernate

spring-boot-starter-security Starter for using Spring Security

Starter for testing Spring Boot applications with


spring-boot-starter-test libraries including JUnit Jupiter, Hamcrest and
Mockito

Starter for using Java Bean Validation with


spring-boot-starter-validation
Hibernate Validator

Starter for building web, including RESTful,


spring-boot-starter-web applications using Spring MVC. Uses Tomcat as the
default embedded container.

spring-boot-starter-web-services Starter for using Spring Web Services

Starter for using Java Mail and Spring Framework’s


spring-boot-starter-mail
email sending support

2. Spring Boot Production Starters


Name Description

Starter for using Spring Boot’s Actuator which


spring-boot-starter-actuator provides production-ready features to help
you monitor and manage your application

3. Spring Boot Technical Starters

Name Description

Starter for using Jetty as the embedded


spring-boot-starter-jetty servlet container. An alternative to spring-
boot-starter-tomcat

Starter for logging using Logback. Default


spring-boot-starter-logging
logging starter

Starter for using Reactor Netty as the


spring-boot-starter-reactor-netty
embedded reactive HTTP server.

Starter for using Tomcat as the embedded


spring-boot-starter-tomcat servlet container. Default servlet container
starter used by spring-boot-starter-web

Auto-Configuration in Spring Boot

Spring Boot is heavily attracting developers toward it because of three main


features as follows:
1. Auto-configuration - such as checking for the dependencies, the presence of
certain classes in the classpath, the existence of a bean, or the activation of some
property.
2. An opinionated approach to configuration.
3. The ability to create stand-alone applications.
Auto-Configuration in Spring Boot
• @Conditional annotation acts as a base for the Spring Boot auto-
configuration annotation extensions.
• It automatically registers the beans with @Component, @Configuration,
@Bean, and meta-annotations for building custom stereotype annotations, etc.
• The annotation @EnableAutoConfiguration is used to enable the auto-
configuration feature.
• The @EnableAutoConfiguration annotation enables the auto-configuration
of Spring ApplicationContext by scanning the classpath components and
registering the beans.
• This annotation is wrapped inside the @SpringBootApplication annotation
along with @ComponentScan and @SpringBootConfiguration annotations.
• When running main() method, this annotation initiates auto-configuration.
• 'spring-boot-autoconfigure.jar' is the file that looks after all the auto-
configuration.
• All auto-configuration logic for MVC, data, JMS, and other frameworks
is present in a single jar


Spring Boot Annotations
Spring Boot applications make extensive use of annotations to simplify
configuration, automate common tasks, and define application structure.

Spring annotations are present in


the org.springframework.boot.autoconfigure and org.springframework.boo
t.autoconfigure.condition packages are commonly known as Spring Boot
annotations

Here are the most important and frequently used annotations in Spring Boot,
with concise explanations:

Spring Boot Annotations List

Some of the annotations that are available in this category are:

• @SpringBootApplication

• @SpringBootConfiguration

• @EnableAutoConfiguration

• @ComponentScan

• Auto-Configuration Conditions

o @ConditionalOnClass, and @ConditionalOnMissingClass

o @ConditionalOnBean, and @ConditionalOnMissingBean

o @ConditionalOnProperty

o @ConditionalOnResource

o @ConditionalOnWebApplication and
@ConditionalOnNotWebApplication

o @ConditionalExpression

o @Conditional

1. @SpringBootApplication
• Combines @Configuration, @EnableAutoConfiguration,
and @ComponentScan.

• Marks the main class of a Spring Boot application and triggers auto-
configuration and component scanning.

2. @RestController

• Combines @Controller and @ResponseBody.

• Used on classes to define RESTful web services; methods return data


(usually JSON) directly as HTTP responses.

3. @RequestMapping / @GetMapping / @PostMapping / @PutMapping /


@DeleteMapping

• Map HTTP requests to handler methods in controller classes.

• @RequestMapping: Generic, can specify method (GET, POST,


etc.) and path.

• @GetMapping, @PostMapping, etc.: Shorthand versions for


specific HTTP verbs.

4. @Autowired

• Marks a field, setter, or constructor to be automatically injected with a


matching bean from the Spring context (dependency injection).

5. @Component / @Service / @Repository / @Controller

• Stereotype annotations for autodetecting and registering beans in the


application context.

• @Component: Generic component.

• @Service: Service layer.

• @Repository: Persistence/DAO layer, with added data access


exception translation.

• @Controller: Web controller.

6. @Configuration
• Marks a class as a source of bean definitions; used to define additional
beans or settings for the Spring context.

7. @Bean

• Declares a bean (object to be managed by the Spring container) from a


method within a class annotated with @Configuration.

8. @Value

• Injects values from properties files (externalized configuration) into


fields, methods, or constructors.

9. @Entity

• Used on Java classes to mark them as database entities (with


JPA/Hibernate), mapping them to database tables.

10. @Table

• Specifies the table in the database that the entity maps to (used
with @Entity).

11. @EnableAutoConfiguration

• Tells Spring Boot to automatically configure the application based on


dependencies in the classpath and external settings.

EXAMPLE:

import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service

public class StudentService {

private final StudentRepository repository;


@Autowired

public StudentService(StudentRepository repository) {

this.repository = repository;

public List<Student> getAllStudents() {

return repository.findAll();

public Student addStudent(Student student) {

return repository.save(student);

public void deleteStudent(Long id) {

repository.deleteById(id);

Spring Boot Project Structure, Packaging, Directory


Layout, and Best Practices
A well-structured Spring Boot project enhances maintainability, collaboration, and
scalability. Although Spring Boot doesn't enforce a specific layout, both
community best practices and official recommendations converge on certain
conventions for directory structure and packaging.
1. Standard Project Structure
Spring Boot aligns with Maven and Gradle's standard directory layout. This
familiar approach makes navigation intuitive and allows build tools to detect
configurations automatically.
Typical Directory Layout:
• src/main/java: Java source code, organized by feature or layer.
• src/main/resources: Configuration files
(application.properties or application.yml), templates (for Thymeleaf,
FreeMarker), static assets (HTML, CSS, JS).
• src/test/java & src/test/resources: Unit/integration tests and configs.
• Root build file: pom.xml (Maven) or build.gradle (Gradle)

2. Project Packaging: JAR vs. WAR


• JAR: Default and recommended. Creates a stand-alone application with
embedded Tomcat/Jetty; run using java -jar yourapp.jar. Ideal for microservices
and cloud deployments.
• WAR: Used if deploying on external servlet containers. Requires
altering pom.xml <packaging>war</packaging> and minor setup changes.
Build tools like Maven/Gradle include plugins to automate packaging and embed
dependencies.
3. Organizing Code
Best practices for directory layout:
• By Layer: Group by controllers, services, repositories, models/entities,
configuration, etc. Good for small/medium projects.
• By Feature/Module: Group everything related to one feature
(e.g., order, customer) in a single package. Preferred for large or modular
codebases, making it easy to find all relevant code for a given feature.
• Use clear naming conventions and avoid the default package (unnamed
package), as Spring component scanning relies on correct packages.
4. Creating and Running a Spring Boot Project
Step-by-step (using Spring Initializr):
1. Go to Spring Initializr.
2. Fill in project metadata (Group, Artifact, Java version, packaging—
JAR/WAR).
3. Select dependencies (e.g., Web, JPA).
4. Generate and unzip the project.
5. Import into your favorite IDE (Eclipse, IntelliJ, VSCode).
6. The generated project uses best-practice layout, ready for coding.
Run the project:
• From IDE: Run the main() method in the class annotated
with @SpringBootApplication.
• From command line:
• mvn spring-boot:run (Maven)
• ./gradlew bootRun (Gradle)
• Or, after packaging: java -jar target/yourapp.jar
By default, the app is accessible at http://localhost:8080/.
5. Additional Best Practices
• Place your main @SpringBootApplication class in the root package.
• Separate application logic from configuration.
• Tests mirror the main source structure.
• Externalize configuration in application.properties/application.yml.
• Use clear, consistent package names (e.g., reverse-domain
e.g., com.example.project).
• Modularize by feature for complex domains or microservices
EXAMPLE PROGRAM :
package com.geeksforgeeks.SpringBootHelloWorld.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

// Marking this class as a REST controller


@RestController
public class HelloWorldController {

// Mapping the root URL ("/") to this method


@RequestMapping("/")
public String helloWorld() {

// Returning a simple "Hello World" response


return "Hello World";
}
}

You might also like