0% found this document useful (0 votes)
49 views89 pages

Spring Framework

The Spring Framework is a Java-based framework designed for building web applications and backend services, offering features like Dependency Injection, Aspect-Oriented Programming, and built-in security. It supports various application types, integrates easily with databases, and facilitates fast development through Spring Boot. The framework's modular architecture allows developers to use only the necessary components, making it lightweight and efficient for projects, including microservices and cloud applications.

Uploaded by

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

Spring Framework

The Spring Framework is a Java-based framework designed for building web applications and backend services, offering features like Dependency Injection, Aspect-Oriented Programming, and built-in security. It supports various application types, integrates easily with databases, and facilitates fast development through Spring Boot. The framework's modular architecture allows developers to use only the necessary components, making it lightweight and efficient for projects, including microservices and cloud applications.

Uploaded by

shaik.asiya1712
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 89

Spring Framework:

1. Introduction to Spring Framework


What is it?
Spring is a Java-based framework used to build web applications and backend
services. It provides tools and libraries that make it easier to develop, test, and
manage large Java applications.
Real-Time Example:
Imagine you're building a banking app. Instead of writing everything from
scratch—security, database handling, web interface—Spring provides ready-
made features to handle these parts efficiently.
 ✅ Easy to Use
 You can build applications with less code using simple Java classes.
 🔁 Handles Dependencies Automatically
 Spring gives you the required objects automatically (no need to create
them yourself).
 🧱 Build Any Type of App
 You can create web apps, REST APIs, mobile backends, desktop apps, etc.
 🔐 Built-in Security
 It provides login, logout, and role-based access easily.
 🚀 Fast Development with Spring Boot
 Spring Boot helps you start projects quickly without too much setup.
 ⚙️Connects with Databases Easily
 Supports JDBC, JPA, Hibernate for storing and getting data.
 📦 Modular (Use What You Need)
 You don’t have to use the whole Spring framework—just the parts you
need.
 🧪 Easy to Test
 Spring apps are easy to test using tools like JUnit and Mockito.
 ☁️Good for Microservices and Cloud
 Works great for creating small services and deploying to the cloud.
 👨‍💻 Large Community Support
Key Features of Spring Framework (Simple Explanation)
1. ✅ Lightweight
o Uses less memory and is faster to run.
2. 🔁 Dependency Injection (DI)
o Spring automatically gives the required objects to your classes.
3. 🔄 Inversion of Control (IoC)
o You don't create objects manually; Spring manages them for you.
4. 🔐 Spring Security
o Easy to add login, logout, and role-based access control.
5. 🧱 Modular Architecture
o You can use only the parts you need (like Spring MVC, Spring Data,
etc.).
6. 🌐 Spring MVC
o Helps build web applications following the MVC (Model-View-
Controller) pattern.
7. 📦 Integration Support
o Works well with databases (JDBC, Hibernate), messaging
(RabbitMQ, Kafka), and APIs.
8. 🚀 Spring Boot
o Makes Spring apps easy to create, configure, and run quickly.
9. 🔄 Aspect-Oriented Programming (AOP)
o Allows you to separate cross-cutting concerns like logging and
transactions.
10.🧪 Testing Support
 Built-in tools and annotations make testing easier.
11.☁️Microservices & Cloud Ready
 Perfect for developing cloud-based or microservice applications.
12.📊 Transaction Management
 Handles database transactions easily and securely.
 Core Modules of Spring Framework

Module Name Purpose


Provides the core features like Dependency Injection (DI) and
1. Spring Core
BeanFactory. It’s the foundation of all other modules.
A way to access beans and provides features like
2. Spring Context
Internationalization, Resource loading, Event handling.
Allows you to apply cross-cutting concerns (like logging,
3. Spring AOP
transactions, etc.) using Aspect-Oriented Programming.
Simplifies JDBC operations (working with databases). Reduces
4. Spring JDBC
boilerplate code.
Integrates Spring with ORM frameworks like Hibernate, JPA.
5. Spring ORM
Helps in database operations using objects.
Helps build web applications using Model-View-Controller
6. Spring Web (MVC)
(MVC) architecture.
7. Spring Web Supports real-time communication using WebSockets (like chat
WebSocket apps).
Adds authentication and authorization to your applications
8. Spring Security
(login, roles, etc.).
Provides support for writing and running unit and integration
9. Spring Test
tests.
Supports integration with messaging systems like RabbitMQ,
10. Spring Messaging
Kafka.
11. Spring Transaction Manages database transactions automatically or declaratively.
12. Spring Expression Allows dynamic expression evaluation in XML or annotations
Language (SpEL) (e.g., @Value("#{2 + 2}")).
Spring Framework
 Definition: A lightweight, open-source Java framework for building web,
enterprise, and standalone applications using features like Dependency
Injection, AOP, MVC, etc.
 Example: A REST API built using Spring Boot, connecting to a MySQL
database and returning JSON responses.

☕ Java EE (Jakarta EE) Enterprise Edition


 Definition: A standard set of specifications provided by Oracle (now
Jakarta EE) for building enterprise Java applications (includes Servlets,
JSP, EJB, JPA, etc.).
 Example: A web app using Servlets and JSPs to display product
information fetched using JPA.

🧱 Hibernate
 Definition: A Java-based ORM (Object-Relational Mapping) tool used to
map Java objects to database tables and vice versa.
 Example: A Java class Student is mapped to the students table in the
database using Hibernate annotations like @Entity, @Id, etc.

2. Spring Framework Architecture


Its architecture is designed around two core principles:
 Dependency Injection (DI)
 Aspect-Oriented Programming (AOP)

Spring is made up of modules that help in different tasks:


 Core Container: Handles the basic structure (like wiring parts together).
 Spring AOP: Manages cross-cutting concerns like logging and security.
 Spring JDBC/ORM: Helps in interacting with databases.
 Spring Web MVC: Helps create web applications.
 Spring Security: Adds login and security features.
 Spring Boot: Makes it easier to set up and run Spring applications.
Real-Time Example:
If you're building an e-commerce site, you’ll use:
 Spring Web for the website,
 Spring Security for login/logout,
 Spring JDBC for storing orders,
 Spring Boot to launch the app quickly.

3. 10 Reasons to Use Spring Framework in Projects


1. Lightweight – Doesn’t use too much memory or processing power.
2. Dependency Injection (DI) – Helps manage object creation
automatically.
3. Easy Integration – Works with other technologies like Hibernate,
MyBatis.
4. Modular – Use only what you need.
5. Security – Built-in security features.
6. Transaction Management – Handles database transactions smartly.
7. Testing Support – Easy to write unit tests.
8. Spring Boot – Reduces setup time.
9. Large Community – Plenty of help available online.
10.Good Documentation – Easy to learn and implement.
Real-Time Example:
If you're working on a college management system, Spring lets you build it
faster, test it easily, and manage everything securely.

4. Spring Initializr
What is it?
A web-based tool to create Spring Boot projects quickly. You select options like
project name, Java version, and dependencies, and it gives you a ZIP file to
start coding.
🔗 Website: https://start.spring.io/
Real-Time Example:
You want to create a new API project for a food delivery app. Go to Spring
Initializr, select "Spring Web" and "MySQL", download the project, and start
building right away.

5. Spring vs. Struts in Java


 Spring is a comprehensive, modular framework offering dependency
injection, aspect-oriented programming, and extensive integration
capabilities for enterprise applications.
 Struts: Struct is an action-based MVC framework primarily focused on
web applications, with less flexibility and integration compared to
Spring.

Feature Spring Struts


Popularity More widely used Older, less used today
Learning Curve Easier with Spring Boot Steeper learning curve
Modularity Highly modular Less flexible
Community Support Strong Limited
Performance Better with Spring Boot Slower in comparison
Configuration Uses annotations (easy) XML-based (more complex)
Real-Time Example:
If you're starting a new online ticket booking system, Spring is better suited
than Struts because it’s modern, faster, and has a lot more tools to support
web and mobile apps.

Here’s a simple and step-by-step guide for each topic so you can easily
download, install, and create Spring Boot projects using different IDEs:

✅ 1. How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse)
IDE?
Steps:
1. Go to: https://spring.io/tools
2. Click “Spring Tools 4 for Eclipse”.
3. Choose your OS (Windows/Mac/Linux) and download the ZIP.
4. Unzip the file and open the folder.
5. Double-click on SpringToolSuite4.exe to open it.
6. Select a workspace folder (where your projects will be saved).
7. Done! You’re ready to use Spring Tool Suite (STS).

✅ 2. How to Create and Setup Spring Boot Project in Spring Tool Suite?
Steps:
1. Open Spring Tool Suite.
2. Go to File > New > Spring Starter Project.
3. Fill details like:
o Project Name
o Type: Maven or Gradle (choose Maven)
o Java Version
4. Click Next.
5. Select dependencies like:
o Spring Web
o Spring Data JPA
o MySQL Driver
6. Click Finish.
7. STS will create the project and download dependencies.
8. Your project is ready!

✅ 3. How to Create a Spring Boot Project with IntelliJ IDEA?


Steps:
1. Open IntelliJ IDEA.
2. Click on New Project > Choose Spring Initializr.
3. Fill in:
o Project SDK (Java version)
o Group: e.g. com.example
o Artifact: e.g. demo
4. Click Next.
5. Choose dependencies like:
o Spring Web
o Spring Boot DevTools
6. Click Finish.
7. IntelliJ will download and set up the project.

✅ 4. How to Create and Setup Spring Boot Project in Eclipse IDE?


Steps:
1. Open Eclipse IDE.
2. Go to Help > Eclipse Marketplace.
3. Search for Spring Tools 4 and Install it.
4. Restart Eclipse.
5. Now go to File > New > Spring Starter Project.
6. Fill in the project details and click Next.
7. Choose your dependencies (Spring Web, JPA, etc.).
8. Click Finish and the project is created.

✅ 5. How to Run Your First Spring Boot Application in Spring Tool Suite?
Steps:
1. Open your Spring Boot project in STS.
2. In the src/main/java folder, open the file with @SpringBootApplication
(usually DemoApplication.java).
3. Right-click on the file.
4. Click Run As > Spring Boot App.
5. Console will show “Tomcat started…” and your app is running!
Real-Time Example:
If you created a project with Spring Web, open your browser and go to:
http://localhost:8080 – You’ll see your app is live.

Here is a simple and clear explanation of core Spring Framework concepts with
code examples and definitions where needed:

1. How to Create a Simple Spring Application


Definition: A Spring application is a Java program where Spring is used to
manage the creation and wiring of objects (beans).
Steps:
1. Create a POJO class.
2. Create a beans.xml file for configuration.
3. Load the context and get the bean.
Example:
// HelloWorld.java
public class HelloWorld {
public void sayHello() {
System.out.println("Hello, Spring!");
}
}
<!-- beans.xml -->
<beans xmlns="http://www.springframework.org/schema/beans" ... >
<bean id="helloBean" class="HelloWorld" />
</beans>
// Main.java
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");
HelloWorld hello = (HelloWorld) context.getBean("helloBean");
hello.sayHello();

2. Understanding Inversion of Control (IoC)


Definition: IoC is a design principle where the control of object creation and
dependency management is transferred from the program to the Spring
container.
two types of IOC:
1.Bean Factory
2.Application context
key features of IOC container:
1.dependency injection(ioc can achieve using DI)
2.lifecycle management
3.configuration flexibility
4.loose coupling

3. Spring – BeanFactory
Beans are Java objects that are configured at run-time by Spring IoC
Container. BeanFactory represents a basic IoC container which is a parent
interface of ApplicationContext.
Definition: BeanFactory is the root interface for accessing the Spring container
that manages beans.
BeanFactory factory = new XmlBeanFactory(new
FileSystemResource("beans.xml"));
MyBean obj = (MyBean) factory.getBean("myBean");
4. Spring – ApplicationContext
Definition: ApplicationContext is a more advanced container than BeanFactory.
It supports features like internationalization, event propagation, and
annotation-based configuration.
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");

5. Spring Dependency Injection with Example


Definition: Dependency Injection is a design pattern where Spring injects
required objects (dependencies) into a class at runtime.
public class Student {
private String name;
public void setName(String name) {
this.name = name;
}
public void display() {
System.out.println("Name: " + name);
}
}
<bean id="student" class="Student">
<property name="name" value="Asiya" />
</bean>
Here are the types of Dependency Injection (DI) in Spring (and in general):

Types of Dependency Injection


1. Constructor Injection
o Dependencies are provided through the class constructor.
o Good for mandatory dependencies and makes the object
immutable.
o Example:
public class UserService {
private UserRepository repo;

public UserService(UserRepository repo) {


this.repo = repo;
}
}
2. Setter Injection
o Dependencies are provided through setter methods after the
object is created.
o Useful for optional dependencies or when you want to change
dependencies later.
o Example:
public class UserService {
private UserRepository repo;

public void setUserRepository(UserRepository repo) {


this.repo = repo;
}
3. }
4. Field Injection (using annotations like @Autowired)
o Dependencies are injected directly into the fields.
o Easiest but less preferred because it hides dependencies and
makes testing harder.
o Example:
5. public class UserService {
6. @Autowired
7. private UserRepository repo;
8. }

6. IoC vs Dependency Injection


Definition:
 IoC is the principle.
 DI is a way to implement IoC.
IoC Dependency Injection
Principle Way to implement IoC
Controls object creation Injects dependencies

7. Constructor Injection Example


Definition: Dependency is injected through class constructor.
public class Employee {
private int id;
private String name;

public Employee(int id, String name) {


this.id = id;
this.name = name;
}
}
<bean id="emp" class="Employee">
<constructor-arg value="101" />
<constructor-arg value="Asiya" />
</bean>

8. Setter Injection with Map


Definition: A map of values is injected using setter method.
public class Question {
private Map<Integer, String> answers;
public void setAnswers(Map<Integer, String> answers) {
this.answers = answers;
}
}
<bean id="q" class="Question">
<property name="answers">
<map>
<entry key="1" value="Java" />
<entry key="2" value="Spring" />
</map>
</property>
</bean>
Sure! Here’s Dependency Injection with Factory Method in Spring explained
very simply:

What is Factory Method DI?


 Instead of Spring creating the object directly, it calls a special method
(factory method) that creates and returns the object.
 Spring then uses that object as the bean and injects it where needed.

Simple Example:
1. You have a factory method that makes the object:
public class ConnectionFactory {
public static Connection createConnection() {
return new Connection("MySQL DB");
}
}
2. Tell Spring to use this factory method to get the bean (in XML):
<bean id="connection" class="com.example.ConnectionFactory" factory-
method="createConnection"/>
3. Now Spring will use this connection bean in your classes:
public class UserService {
private Connection connection;

// Inject connection via constructor


public UserService(Connection connection) {
this.connection = connection;
}
}

Why use Factory Method DI?


 When creating the object needs special logic.
 When the object is created by a third-party factory method.
9. Setter Injection with Non-String Map
Definition: Injecting objects into a map with non-string keys and values.
<map>
<entry>
<key><value type="int">1</value></key>
<value><bean class="Answer" /></value>
</entry>
</map>

10. Constructor Injection with Non-String Map


Definition: Map is passed to the constructor of a class.
Same as above, but pass map in constructor.

11. Bean Life Cycle in Spring


Definition: Steps from creation to destruction of a bean.
The lifecycle of a bean in Spring refers to the sequence of events that occur
from the moment a bean is instantiated until it is destroyed.
1. Bean is instantiation
2. Dependencies are injected
3. init() method is called
4. Bean is ready to use
destroy() method is called on shutdown
 Spring allows you to define custom initialization and destruction methods
for your beans.
 These methods run automatically:
 init() → runs after bean creation (initialization phase)
 destroy() → runs before bean is removed from the container
(destruction phase)

public class ExampleBean {


public void init() {
System.out.println("Init method called");
}
public void destroy() {
System.out.println("Destroy method called");
}
}
<bean id="ex" class="ExampleBean" init-method="init" destroy-
method="destroy" />
Ways to Implement the Bean Life Cycle
1. Using XML Configuration
2. Using Programmatic Approach (Interface)
3. Using Annotations
To provide the facility to the created bean to invoke custom init() method on
the startup of a spring container and to invoke the custom destroy() method on
closing the container, we need to annotate init() method
by @PostConstruct annotation and destroy() method
by @PreDestroy annotation.

12. Custom Bean Scope in Spring


Definition: Scope defines how long the bean lives in the container.
Scopes:
 Singleton (default)
 Prototype
Singleton Scope: One instance of the bean is created per Spring IOC
Container. This is the default scope.
 Prototype Scope: A new instance of the bean is created every time it is
requested

 Request
 Session
<bean id="myBean" class="MyBean" scope="prototype" />
How to Create a Spring Bean in 3 Different Ways?
Method 1: Creating Bean Inside an XML Configuration File (beans.xml)
Method 2: Using @Component Annotation
Method 3: Using @Bean Annotation

13. Spring – IoC Container


Definition: Core container that manages beans and their life cycle.
 Types: BeanFactory and ApplicationContext
 BeanFactory Container
 It is the basic and simplest container in Spring that provides basic support for
Dependency Injection (DI) and manages the lifecycle of beans lazily (creates beans
when requested).

 ApplicationContext Container
 It is a more advanced container built on top of BeanFactory that provides
additional features like internationalization, event propagation, and supports eager
loading of beans (creates beans at startup). It is the commonly used container in
Spring applications.

 🌿 Spring Autowiring and Its Modes – Simple Explanation


 ✅ What is Autowiring in Spring?


 Autowiring means Spring automatically injects the required dependencies into a
bean, without needing to explicitly specify them in configuration (like XML or
Java).

 🔄 Autowiring Modes in Spring

Mode Description
no (default) Autowiring is disabled. You must manually define all dependencies.
Spring injects the bean by matching the property name with a bean
byName
ID.
Spring injects the bean by matching the property type with a bean
byType
type.
Spring uses the constructor to inject dependencies by matching
constructor
types.
autodetect Spring chooses between constructor or byType. (Used in older
(deprecated) versions only)

 🧪 Example: @Autowired in Annotation-based Autowiring
 @Component
 public class Car {
 @Autowired
 private Engine engine; // Spring will inject Engine bean
automatically
 }

14. Configure DispatcherServlet in web.xml


Definition: DispatcherServlet is the front controller in Spring MVC to handle all
incoming requests.
A Front Controller is a design pattern, which means it acts as a single entry
point for all requests. It makes things like security, logging, and routing easier
to manage.
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
we configure Dispatcher Servlet in the following three different ways:
1. Configure Dispatcher Servlet in web.xml File
2. Configure Dispatcher Servlet using WebApplicationInitializer
3. Configure Dispatcher Servlet using
AbstractAnnotationConfigDispatcherServletInitializer

15. Spring Expression Language (SpEL)


Definition: SpEL is used for performing calculations, logic, and accessing
properties in Spring XML or annotation configuration.
<bean id="mathBean" class="Calculator">
<property name="sum" value="#{2 + 3}" />
</bean>
What are Spring Application Events?
Spring Application Events are events that are triggered by the Spring
framework. They are designed to be used in the development of applications
that need to be aware of changes in the environment.

a circular dependency is a relation between two or more modules that either


directly or indirectly depend on each other to function properly.

16. RowMapper vs ResultSetExtractor


Definition: Both are used in JDBC template to map database rows to objects.
Feature RowMapper ResultSetExtractor
Usage Maps each row to object Processes full ResultSet
When to use Multiple rows One or complex row
// RowMapper
public class MyRowMapper implements RowMapper<Employee> {
public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Employee(rs.getInt(1), rs.getString(2));
}
}

17. Spring Framework Annotations


Definition: Annotations in Spring are metadata that provide instructions to the
Spring container.
Types of Spring Framework Annotations
 Spring Core Annotations
Spring annotations are present in
the org.springframework.beans.factory.annotation and org.springframe
work.context.annotation packages.
1.dependency injection related annotations

 Annotation  Purpose  Example Usage


 Automatically
 @Autowired private Car
 @Autowired injects a bean
car;
(dependency).
 Specifies which
bean to inject  @Autowired
 @Qualifier when multiple of @Qualifier("electricCar")
the same type private Car car;
exist.
 @Primary  Marks one bean as  @Primary @Bean public
 Annotation  Purpose  Example Usage
the default when
Car car() { return new
multiple
Car(); }
candidates exist.
 Declares a method
as a Spring bean
 @Bean public Car car()
 @Bean producer in
{ return new Car(); }
@Configuration
class.
 Defines the scope  @Bean
of a bean (e.g., @Scope("prototype")
 @Scope
singleton, public Car car() { return
prototype). new Car(); }
 Injects values from
property files or  @Value("${app.name}")
 @Value
constants into private String appName;
fields.
 Delays bean
 @Lazy @Autowired
 @Lazy creation until first
private HeavyService hs;
use.
 Ensures a
property must be
 @Required set via a setter  @Required public void
(deprecated) method. (Used in setName(String name)
older Spring
versions)
 Tells Spring to
return a new
 @Lookup public abstract
 @Lookup instance from
Service getService();
container at
runtime.

2.context configuration annotations
Here is the updated simple table without the "Used On" column:
 Annotation  Purpose  Example
 Declares a
 @Bean public MyService
bean to be
 @Bean myService() { return new
managed
MyService(); }
by Spring.
 Marks a
class as a
 @Componen Spring-  @Component class MyComponent
t managed {}
componen
t (bean).
 Specifies
the profile
under  @Profile("dev") @Component
 @Profile
which the class DevComponent {}
componen
t is active.
 Imports
additional
 @Import @Configur  @Import(AppConfig.class)
ation
classes.
 Loads
Spring
bean
 @ImportRes
definitions  @ImportResource("beans.xml")
ource
from XML
configurati
on files.
 @PropertyS  Loads  @PropertySource("classpath:app.
ource property
 Annotation  Purpose  Example
files into
Spring
properties")
Environme
nt.

 Spring Web Annotations


Spring Web annotations are present in
the org.springframework.web.bind.annotation package.
@Controller: This annotation marks a class as a Spring MVC controller. It
is used with @RequestMapping to handle web requests.
@RequestMapping: This annotation maps HTTP requests to handler
methods in the controller.
 @RequestBody: This annotation binds the body of the HTTP request to a
Java object.
 @PathVariable: This annotation extracts values from the URI template.
 @RequestParam: This annotation extracts query parameters from the
URL.
 @ResponseBody: This annotation indicates that the return value of the
method should be used as the response body.
 @ExceptionHandler: This annotation is used to handle exceptions
thrown by request-handling methods.
 @ResponseStatus: This annotation specifies the HTTP status code for
the response.
 @RestController: This annotation is a combination of @Controller and
@ResponseBody, used for RESTful web services.
 @ModelAttribute: This annotation binds a method parameter or
method return value to a named model attribute.
 @CrossOrigin: This annotation enables cross-origin resource sharing
(CORS) for specific handler methods or controller classes.

 Spring Boot Annotations
Spring Boot annotations are present in
the org.springframework.boot.autoconfigure and org.springframework.
boot.autoconfigure.condition packages.
@SpringBootApplication: This annotation is used to mark the main class
of a Spring Boot application. It encapsulates @Configuration,
@EnableAutoConfiguration, and @ComponentScan annotations with
their default attributes.
@EnableAutoConfiguration: This annotation enables Spring Boot’s auto-
configuration mechanism.
 @ConditionalOnClass: This annotation configures a bean only if a
specified class is present on the classpath.
 @ConditionalOnMissingBean: This annotation configures a bean only if
a specified bean is not already present in the application context.

 Spring Scheduling Annotations


Spring Scheduling annotations are present in
the org.springframework.scheduling.annotation package.
@EnableAsync: This annotation enables asynchronous processing in
Spring.
 @EnableScheduling: This annotation enables scheduling in Spring.
 @Async: This annotation marks a method to be executed
asynchronously.
 @Scheduled: This annotation marks a method to be executed on a fixed
schedule.

 Spring Data Annotations


Spring Data annotations provide an abstraction over data storage
technologies.
@Transactional: This annotation marks a method or class as
transactional.
@Id: This annotation marks a field in a model class as the primary key.
@Query: This annotation defines custom queries for repositories.
 @Procedure: This annotation marks a method for calling a stored
procedure.
 @Lock: This annotation specifies locking behavior for methods.
 @Modifying: This annotation marks a query as modifying (e.g., for
update or delete operations).
 @EnableJpaRepositories: This annotation enables JPA repositories in a
Spring application.
 @Document (MongoDB): This annotation marks a class as a MongoDB
document.
 @Field (MongoDB): This annotation specifies a field in a MongoDB
document.

 Spring Bean Annotations


Spring Bean annotations are used to configure beans in a Spring
container.
@ComponentScan: This annotation is used to specify the base
packages for scanning components.
 @Configuration: This annotation indicates that the class can be used by
the Spring IoC container as a source of bean definitions.
 @Stereotype: This annotaion is used to automatically register beand in
the spring context based on their roles.
19. Spring Stereotype Annotations
Definition: Used to define Spring-managed components.
 @Component - generic stereotype
 @Service - marks a service class
 @Repository - marks DAO class
 @Controller - marks web controller
@Component: This annotation is a generic stereotype for any Spring-
managed component.
 @Service: This annotation is used to indicate that a class holds business
logic.
 @Repository: This annotation is used to indicate that a class deals with
CRUD operations, typically used with DAO or Repository
implementations.
 @Controller: This annotation is used to indicate that a class is a front
controller, responsible for handling user requests.

20. @Bean Annotation


Definition: Declares a bean to be managed by Spring.
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
21. @Controller Annotation
Definition: Marks a class as Spring MVC controller.
@Controller
public class MyController {
@RequestMapping("/hello")
public String sayHello() {
return "hello";
}
}
22. @Value Annotation
Definition: Injects values into variables.
@Value("${user.name}")
private String userName;
23. @Configuration Annotation
Definition: Marks a class as a configuration class that defines beans.
@Configuration
public class AppConfig {
// bean definitions
}
24. @ComponentScan Annotation
Definition: Enables component scanning.
@ComponentScan(basePackages = "com.example")
25. @Qualifier Annotation
Definition: Used to resolve ambiguity when multiple beans of same type exist.
@Autowired
@Qualifier("bean1")
private MyBean myBean;
26. @Service Annotation
Definition: Marks a class as a service component.
@Service
public class UserService {
// business logic
}
27. @Repository Annotation
Definition: Marks a class as a DAO (Data Access Object).
@Repository
public class UserRepository {
// data access code
}
28. @Required Annotation
Definition: Ensures a property is set.
@Required
public void setName(String name) {
this.name = name;
}
29. @Component Annotation
Definition: Generic stereotype for a Spring-managed component.
@Component
public class MyComponent {
// some logic
}
30. @Autowired Annotation
Definition: Automatically injects bean dependencies.
@Autowired
private MyService myService;
Sure! Here's the definition and syntax of @PropertySource:
 Definition:
@PropertySource is used to load .properties files into the Spring
Environment so you can access their values using @Value or the
Environment object.
 Syntax:
 @PropertySource("classpath:filename.properties")
31. @Scope Annotation
Definition: Sets the scope of a Spring bean.
@Component
@Scope("prototype")
public class MyBean {}

Let me know if you want a project setup using any of these!


Here is a complete explanation of each Spring Boot topic you asked for, clearly
organized and easy to understand:

🌟 Introduction to Spring Boot


Spring Boot is a framework built on top of the Spring Framework. It simplifies
the development of stand-alone, production-grade Spring applications with
minimal configuration.
Key Features:
 Auto-configuration
 Embedded servers (Tomcat, Jetty)
 Starter dependencies
 Actuator for monitoring
 Spring Initializr support

🚀 How to Create a Spring Boot Project?


You can create a Spring Boot project in the following ways:
1. Using Spring Initializr (start.spring.io)
2. Using Spring Tool Suite (STS) → File → New → Spring Starter Project
3. Using IDE (like IntelliJ) with Spring Boot plugin
Choose dependencies like Spring Web, Spring Data JPA, Spring Boot DevTools,
etc., and download the project.
How to Run Your First Spring Boot Application in Spring Tool Suite?
1. Import the Spring Boot project into STS.
2. Locate the main class with @SpringBootApplication.
3. Right-click → Run As → Spring Boot App.
4. The embedded Tomcat server starts, and the app runs on
http://localhost:8080.

springboot annotations
Here’s a simple table with definitions and syntax for each Spring Boot
annotation and condition you mentioned:
Annotation Definition Syntax Example
Combines
@SpringBootConfi
guration,
@SpringBootApplicatio @SpringBootApplication public
@EnableAutoCon
n class App {}
figuration, and
@ComponentScan
in one.
Indicates a Spring
@SpringBootConfigurati Boot configuration @SpringBootConfiguration public
on class (like class Config {}
@Configuration).
Enables Spring
Boot’s auto-
@EnableAutoConfigura configuration @EnableAutoConfiguration
tion feature to public class Config {}
configure beans
automatically.
@ComponentScan Tells Spring where @ComponentScan(basePackages
to look for = "com.example")
Annotation Definition Syntax Example
components,
configurations,
and services.
Conditions used
by Spring Boot to
Auto-Configuration enable or disable
(Used internally in Spring Boot)
Conditions auto-configuration
based on
environment.
Applies
configuration only @ConditionalOnClass(name =
@ConditionalOnClass
if specified class is "com.example.Foo")
on the classpath.
Applies
configuration only
@ConditionalOnMissing @ConditionalOnMissingClass("co
if specified class is
Class m.example.Bar")
NOT on the
classpath.
Applies
configuration only
@ConditionalOnBean(name =
@ConditionalOnBean if a specific bean
"myBean")
exists in the
context.
Applies
configuration only
@ConditionalOnMissing @ConditionalOnMissingBean(My
if a specific bean is
Bean Service.class)
missing from the
context.
@ConditionalOnPropert Applies @ConditionalOnProperty(name =
y configuration only "app.feature.enabled",
if a specific havingValue = "true")
property has a
Annotation Definition Syntax Example
defined value.
Applies
@ConditionalOnResource(resour
@ConditionalOnResour configuration only
ces =
ce if a specified
"classpath:myfile.properties")
resource exists.
Applies
configuration only
@ConditionalOnWebAp
if the application @ConditionalOnWebApplication
plication
is a web
application.
Applies
configuration only
@ConditionalOnNotWe @ConditionalOnNotWebApplica
if the application
bApplication tion
is NOT a web
application.
Applies
configuration
based on a SpEL @ConditionalExpression("$
@ConditionalExpression
(Spring Expression {my.property:true}")
Language)
expression.
General purpose
conditional
@Conditional annotation that @Conditional(MyCondition.class)
takes a custom
condition class.
If you want, I can give you brief examples or explain any of these further!
Request Handling and Controller annotations:
Here’s a simple table with definitions and syntax for important Spring MVC
request handling and controller annotations you mentioned:
Annotation Definition Syntax Example
Marks a class as a
Spring MVC
controller to
@Controller public class
@Controller handle HTTP
MyController { }
requests and return
views (usually
HTML).
Combines
@Controller and
@ResponseBody; @RestController public class
@RestController
returns JSON/XML ApiController { }
directly instead of
views.
Maps HTTP
requests (GET,
POST, etc.) to @RequestMapping("/users") or
@RequestMapping handler methods or @RequestMapping(value="/users",
classes; can specify method = RequestMethod.GET)
path, method,
params.
Binds a HTTP
request parameter public String
@RequestParam
to a method getUser(@RequestParam String id)
parameter.
Binds a URI
@GetMapping("/users/{id}") public
template variable
@PathVariable String getUser(@PathVariable String
to a method
id)
parameter.
Binds the HTTP
request body to a
public Response
@RequestBody method parameter,
addUser(@RequestBody User user)
typically for
JSON/XML input.
Annotation Definition Syntax Example
Indicates that the
method return
value is the @ResponseBody public String hello()
@ResponseBody
response body { return "Hi"; }
(instead of a view
name).
Binds form data to
a model object and public String
@ModelAttribute makes it available submitForm(@ModelAttribute User
to views or user)
controller methods.
If you want, I can provide code examples for each!

🧱 Spring Boot – Architecture


Spring Boot follows a layered architecture:
1. Presentation Layer – Controllers (handling HTTP requests)
2. Business Layer – Services (business logic)
3. Data Access Layer – Repositories (interacting with DB)
4. Auto Configuration – Automatically configures beans based on classpath
settings.
5. Embedded Server – Comes with Tomcat/Jetty, no need to deploy WAR
separately.

⚙️Spring Boot – Application Properties


The application.properties or application.yml file is used for external
configuration of the application.
Examples:
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.jpa.hibernate.ddl-auto=update

📦 Spring Boot – Dependency Management


Spring Boot manages versions of libraries via its dependency management
system, eliminating conflicts and ensuring compatibility.
 Uses a parent starter:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.0</version>
</parent>

🚀 Spring Boot – Starters


Spring Boot Starters are dependency descriptors, essentially pre-configured
sets of libraries, that simplify dependency management in Spring
applications. They bundle common libraries for specific functionalities,
allowing developers to quickly add features without manually managing
dependencies.
Here are some common types of Spring Boot Starters:
 spring-boot-starter-web: For building web applications, including
RESTful services, using Spring MVC and an embedded Tomcat server.
 spring-boot-starter-data-jpa: Simplifies database interactions using JPA
and Hibernate.
 spring-boot-starter-jdbc: Provides support for JDBC database
connections.
 spring-boot-starter-test: Includes testing libraries like JUnit, Mockito,
and Spring Test for unit and integration testing.
 spring-boot-starter-security: Adds security features to applications.
 spring-boot-starter-cache: Enables caching support.
 spring-boot-starter-web-services: For creating web services.
 spring-boot-starter-hateoas: Adds features related to HATEOAS.
 spring-boot-starter: Core starter that includes auto-configuration,
logging, and YAML support.
 spring-boot-starter-aop: For aspect-oriented programming using Spring
AOP and AspectJ.

👋 Spring Boot – Hello World Example


Steps:
1. Create a Spring Boot project.
2. Add a Controller class:
@RestController
public class HelloController {
@GetMapping("/")
public String hello() {
return "Hello, Spring Boot!";
}
}
3. Run the app → Go to http://localhost:8080

🌐 Spring Boot – REST Example


Create REST APIs using @RestController.
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users")
public List<User> getAllUsers() {
return userService.findAll();
}
}
You can test using Postman or Swagger.

🧪 Spring Boot – Starter Test


The spring-boot-starter-test includes testing libraries:
 JUnit 5
 Mockito
 Spring Test
 AssertJ
Example:
@SpringBootTest
public class MyTest {
@Test
void testAppRuns() {
assertEquals(2, 1 + 1);
}
}

🔁 Spring Boot – Spring JDBC vs Spring Data JDBC


Feature Spring JDBC Spring Data JDBC
Manual (Template, Automatic with repository
Configuration
RowMapper) support
Abstraction
Low-level Mid-level
Level
Ease of Use More code Less boilerplate
CRUD Interface-based (e.g.
Manual
Operations CrudRepository)

⚠️Spring Boot – Exception Handling


Exception handling in Spring Boot can be done using:
 @ControllerAdvice for global exceptions
 @ExceptionHandler for specific errors
Example:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> handleNotFound(ResourceNotFoundException ex)
{
return
ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
}

📊 Spring Boot – Actuator


Spring Boot Actuator provides production-ready features to monitor and
manage your application.
Features:
 Health checks
 Metrics (CPU, memory, DB)
 Application info
 Environment properties
Enable endpoints:
management.endpoints.web.exposure.include=*
Access:
 http://localhost:8080/actuator/health
 http://localhost:8080/actuator/metrics

Introduction to RESTful Web Services


 RESTful Web Services a way for different systems (like websites or apps)
to talk to each other on the internet,using principles of REST
(Representational State Transfer) architecture. They use standard HTTP
methods and URLs to perform operations on resources.

 Key Concepts:
 Resource:
Anything you want to expose via the web, identified by a URL (Uniform
Resource Locator). For example, a user, product, or order.
 HTTP Methods:
RESTful services use HTTP methods to perform operations on resources:
 GET: Retrieve resource(s)
 POST: Create a new resource
 PUT: Update an existing resource
 DELETE: Remove a resource
 Stateless:
Each request from the client is independent of previous ones, meaning
the server doesn't need to remember what the client was doing in
previous requests.
 Representation:
Resources can be represented in different formats, commonly JSON or
XML.

 Why Use RESTful Web Services?


 Lightweight and easy to use over HTTP.
 Platform and language independent.
 Uses standard HTTP status codes for responses.
 Simple and scalable architecture.
 Easily consumable by web, mobile apps, and IoT devices.

 Example
 A RESTful API to manage users might have URLs like:
 GET /users — Get list of users
 GET /users/{id} — Get user details by ID
 POST /users — Create new user
 PUT /users/{id} — Update user details
 DELETE /users/{id} — Delete a user

 Creating a REST API using Java Spring Boot is straightforward. Here's a
simple step-by-step guide to get you started:

 Step 1: Setup Spring Boot Project


 Use Spring Initializr or your IDE to create a new Spring Boot project.
 Choose:
 Project: Maven or Gradle
 Dependencies: Spring Web

 Step 2: Create a Model Class


 Define a simple data model to represent your resource. For example, a
User:
 public class User {
 private Long id;
 private String name;
 private String email;

 // Constructors, getters, setters


 }

 Step 3: Create a Controller


 Create a controller to handle HTTP requests.
 import org.springframework.web.bind.annotation.*;

 import java.util.*;

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

 private Map<Long, User> userMap = new HashMap<>();


 @GetMapping
 public Collection<User> getAllUsers() {
 return userMap.values();
 }

 @GetMapping("/{id}")
 public User getUserById(@PathVariable Long id) {
 return userMap.get(id);
 }

 @PostMapping
 public String createUser(@RequestBody User user) {
 userMap.put(user.getId(), user);
 return "User created successfully";
 }

 @PutMapping("/{id}")
 public String updateUser(@PathVariable Long id, @RequestBody User
user) {
 userMap.put(id, user);
 return "User updated successfully";
 }

 @DeleteMapping("/{id}")
 public String deleteUser(@PathVariable Long id) {
 userMap.remove(id);
 return "User deleted successfully";
 }
 }

 Step 4: Run the Application


 Run the Spring Boot application.
 Use tools like Postman or curl to test your API:
 GET http://localhost:8080/users
 POST http://localhost:8080/users
 PUT http://localhost:8080/users/{id}
 DELETE http://localhost:8080/users/{id}

 Summary:
 Step  Description
 1  Create Spring Boot project with Spring Web dependency
 2  Define model class
 Create REST controller with mappings for GET, POST, PUT,
 3
DELETE
 4  Run and test API

 If you want, I can help you with a complete Maven project structure or
database integration!

Here’s a clear comparison table between Spring MVC and Spring Boot:
Aspect Spring MVC Spring Boot
A framework to quickly create
A web framework for
stand-alone, production-ready
Definition building MVC-based web
Spring applications with minimal
applications using Spring.
configuration.
Requires manual
Auto-configuration reduces
configuration of
Configuration manual setup; embedded server
DispatcherServlet,
included.
ViewResolvers, etc.
Setup More complex, needs explicit Simplified setup with starter
Complexity setup and dependencies. dependencies and defaults.
Needs external servlet Comes with embedded server
Server
container (Tomcat, Jetty) (Tomcat, Jetty, or Undertow).
Generates WAR files to Generates executable JAR files
Deployment
deploy on external servers. with embedded server.
Development Slower due to more Faster with auto-configuration
Speed boilerplate and config. and opinionated defaults.
Good for existing Spring apps Ideal for new projects needing
Use Case
and fine-tuned control. quick startup and microservices.
Less opinionated, flexible but Highly opinionated for
Opinionated
verbose. convention over configuration.

In short:
 Spring MVC is a web framework focused on building web apps with MVC
pattern.
 Spring Boot is a starter toolkit to quickly create Spring applications
(including MVC apps) with less hassle.
Want me to help you start a Spring Boot project from scratch?

🌐 1. Introduction to Spring MVC


Spring MVC (Model-View-Controller) is a framework within Spring for building
web applications. It follows the MVC design pattern which separates:
 Model – The data or business logic
 View – The UI (e.g., JSP, Thymeleaf)
 Controller – Handles HTTP requests and maps them to the appropriate
services or models.
Key Features:
 DispatcherServlet
 Annotations like @Controller, @RequestMapping
 Form handling and data binding
 Integration with view technologies

🧩 2. Spring MVC using Java-based configuration


Instead of using web.xml, Spring MVC can be configured using Java classes.
Example:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.example")
public class WebConfig implements WebMvcConfigurer { }
public class AppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return null;
}

protected Class<?>[] getServletConfigClasses() {


return new Class[] { WebConfig.class };
}

protected String[] getServletMappings() {


return new String[] { "/" };
}
}

⚙️3. Create and Run Your First Spring MVC Controller in Eclipse/STS
Steps:
1. Create a Spring MVC project.
2. Add dependencies (Spring Web, Servlet API).
3. Create a controller:
@Controller
public class HomeController {
@RequestMapping("/")
public String home() {
return "index"; // View name (index.jsp)
}
}
4. Create a view file index.jsp inside /WEB-INF/views.
5. Configure a ViewResolver to locate the view.
📦 4. How to Create Your First Model in Spring MVC?
Example:
public class User {
private String name;
private String email;
// getters and setters
}
You can use this model in the controller:
@RequestMapping("/user")
public String getUser(Model model) {
User user = new User("Asiya", "[email protected]");
model.addAttribute("user", user);
return "user-view";
}

5. How to Create Your First View in Spring MVC?


 Views are typically JSP, Thymeleaf, or HTML pages.
 Place JSP files in:
/WEB-INF/views/
Example – user-view.jsp:
<html>
<body>
<h1>User Info</h1>
Name: ${user.name} <br>
Email: ${user.email}
</body>
</html>
🔍 6. ViewResolver in Spring MVC
A ViewResolver maps the logical view names returned by the controller to
actual view resources.
Java-based config:
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new
InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
If controller returns "home", Spring will look for /WEB-INF/views/home.jsp.

📥 7. Spring MVC - @RequestParam Annotation


@RequestParam is used to extract query parameters from the URL and bind
them to method parameters.
Example:
@RequestMapping("/greet")
public String greetUser(@RequestParam("name") String name, Model model) {
model.addAttribute("message", "Hello, " + name);
return "greet";
}
URL: http://localhost:8080/greet?name=Asiya
Output: "Hello, Asiya"
🔁 1. Spring @RequestMapping Annotation with Example
@RequestMapping is used to map HTTP requests to handler methods in
controllers.
Example:
@Controller
public class HelloController {

@RequestMapping(value = "/hello", method = RequestMethod.GET)


public String sayHello() {
return "hello"; // Maps to hello.jsp
}
}
You can also map by path:
@RequestMapping("/welcome")
public String welcomePage() {
return "welcome";
}

⚖️2. Difference Between @Controller and @RestController in Spring


Feature @Controller @RestController
Used in Spring MVC for
Purpose Used for REST APIs
web apps
Returns view names (e.g.,
Return Type Returns data (usually JSON)
JSP)
Annotation Combines @Controller +
Class-level annotation
Type @ResponseBody
Use Case Web applications (UI- RESTful web services (API-based)
Feature @Controller @RestController
based)
Example:
// Web controller
@Controller
public class PageController {
@GetMapping("/home")
public String home() {
return "index"; // returns index.jsp
}
}

// REST controller
@RestController
public class ApiController {
@GetMapping("/api/hello")
public String hello() {
return "Hello, World"; // returns plain text/JSON
}
}

⚠️3. Spring MVC – Exception Handling


Spring MVC provides multiple ways to handle exceptions:
 @ExceptionHandler: t is used on methods within a controller
or @ControllerAdvice class.
 Specifies the type of exception the method will handle.
 @ControllerAdvice: t is used on classes to define a global exception
handler.
 ResponseEntityExceptionHandler
Example:
@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return new ResponseEntity<>("Something went wrong: " +
ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

📥 4. How to Capture Data using @RequestParam Annotation in Spring?


@RequestParam captures form or query parameters from the request URL.
Example:
@Controller
public class FormController {

@PostMapping("/submit")
public String submitForm(@RequestParam("username") String name, Model
model) {
model.addAttribute("name", name);
return "result";
}
}
HTML Form:
<form action="/submit" method="post">
<input name="username">
<input type="submit">
</form>

🧑‍⚕️5. Spring MVC – Sample Project: Finding Doctors Online with MySQL
Features:
 Search doctors by name or specialization
 Store doctor data in MySQL
 Display list of matching doctors
Tech Stack: Spring MVC + JSP + MySQL + JDBC
Basic Flow:
1. Model: Doctor.java – id, name, specialization, contact
2. DAO Layer: CRUD operations on doctor table
3. Controller: Accept search query using @RequestParam
4. View: Show list of doctors in result.jsp

✅ 6. Spring MVC - Custom Validation


Create custom validation rules using @Constraint, Validator, and Bean
Validation (javax.validation).
Steps:
1. Create Custom Annotation:
@Constraint(validatedBy = NameValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidName {
String message() default "Invalid name";
}
2. Implement Validator:
public class NameValidator implements ConstraintValidator<ValidName,
String> {
public boolean isValid(String name, ConstraintValidatorContext ctx) {
return name != null && name.matches("[A-Za-z ]+");
}
}
3. Apply to Model Field:
public class User {
@ValidName
private String name;
}

📁 7. Spring MVC File Upload


Spring MVC supports file uploads using MultipartFile.
Example:
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
// Save file to disk
}
return "upload-success";
}
form.jsp:
<form method="POST" enctype="multipart/form-data" action="/upload">
<input type="file" name="file"/>
<input type="submit" value="Upload"/>
</form>

8. Spring MVC Integration with MySQL


Steps:
1. Add MySQL dependency.
2. Configure application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/dbname
spring.datasource.username=root
spring.datasource.password=yourpassword
3. Use JdbcTemplate or Spring Data JPA for DB interaction.

🔄 9. Spring MVC CRUD with Example


Operations:
 Create Doctor
 Read/View Doctor
 Update Doctor
 Delete Doctor
Basic Code Snippets:
Create:
@PostMapping("/add")
public String addDoctor(@ModelAttribute Doctor doctor) {
doctorService.save(doctor);
return "redirect:/list";
}
Read:
@GetMapping("/list")
public String viewDoctors(Model model) {
model.addAttribute("doctors", doctorService.findAll());
return "doctor-list";
}
Update:
@GetMapping("/edit/{id}")
public String editDoctor(@PathVariable int id, Model model) {
model.addAttribute("doctor", doctorService.findById(id));
return "edit-doctor";
}
Delete:
@GetMapping("/delete/{id}")
public String deleteDoctor(@PathVariable int id) {
doctorService.delete(id);
return "redirect:/list";
}

 Here's a detailed explanation of each Spring REST API topic you


requested, covering concepts, examples, and best practices:
API (Application Programming Interface):
Think of it as a set of instructions or tools that tell one system how to interact
with another system.
 REST (Representational State Transfer):
This is a style or set of guidelines for designing APIs that are easy to use and
understand.
 HTTP (Hypertext Transfer Protocol):
The language used to communicate over the internet. REST APIs use HTTP
methods like GET, POST, PUT, and DELETE to request data or perform actions.

🌐 1. Spring – REST Controller


A REST Controller in Spring is a specialized version of @Controller used to
create RESTful web services. It combines @Controller and @ResponseBody.
@RestController
public class MyRestController {

@GetMapping("/hello")
public String hello() {
return "Hello from REST Controller";
}
}

🚀 2. Spring Boot – Introduction to RESTful Web Services


RESTful web services use HTTP requests to perform CRUD operations. Spring
Boot simplifies building REST APIs with embedded servers, starter
dependencies, and minimal setup.
Key HTTP methods:
 GET – retrieve resources
 POST – create resources
 PUT – update resources
 DELETE – remove resources

⚙️3. How to Make a Simple RestController in Spring Boot?


Steps:
1. Create a Spring Boot project with spring-boot-starter-web.
2. Add a @RestController class.
3. Define endpoints using annotations like @GetMapping, @PostMapping.
@RestController
public class SimpleRestController {
@GetMapping("/greet")
public String greet() {
return "Hello, Spring Boot REST!";
}
}

📦 4. How to create a REST API using Java Spring Boot


Example – Simple CRUD REST API for User:
@RestController
@RequestMapping("/api/users")
public class UserController {

@GetMapping
public List<User> getAllUsers() {
return userService.findAll();
}

@PostMapping
public User createUser(@RequestBody User user) {
return userService.save(user);
}
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}

@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.update(id, user);
}

@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.delete(id);
}
}

🔄 5. Spring REST JSON Response


Spring Boot automatically converts Java objects returned from REST controllers
into JSON using the Jackson library.
Example:
@GetMapping("/user")
public User getUser() {
return new User(1L, "Asiya", "[email protected]");
}
This returns JSON like:
{
"id": 1,
"name": "Asiya",
"email": "[email protected]"
}

📝 6. Spring – REST XML Response


Spring can also send XML responses if configured.
Add dependency:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Example:
@GetMapping(value = "/user/xml", produces =
MediaType.APPLICATION_XML_VALUE)
public User getUserXML() {
return new User(1L, "Asiya", "[email protected]");
}

7. JSON using Jackson in REST API Implementation with Spring Boot


Jackson is the default JSON processor in Spring Boot. It serializes Java objects to
JSON and vice versa.
Features:
 Use @JsonIgnore to hide fields.
 Use @JsonProperty to rename fields in JSON.
 Custom serializers/deserializers supported.
🔄 8. Spring – RestTemplate
RestTemplate is a synchronous client to consume RESTful web services
RestTemplate is a Spring Framework class used for making synchronous HTTP
requests. .
Example:
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("https://api.example.com/users",
String.class);
You can also post data:
User newUser = new User("Asiya");
User createdUser =
restTemplate.postForObject("https://api.example.com/users", newUser,
User.class);

⚡ 9. Easiest Way to Create REST API using Spring Boot


Use Spring Initializr to create a project with the spring-boot-starter-web
dependency, then:
 Create a model class
 Create a @RestController
 Use @GetMapping, @PostMapping etc. to handle endpoints
 Spring Boot handles embedded server and JSON serialization

🌱 1. Introduction to the Spring Data Framework


Spring Data is a Spring-based programming model that simplifies data access
and manipulation. It provides an abstraction over various data stores
(relational, NoSQL, etc.) and reduces boilerplate code for database operations.
Main features:
 Repository interfaces for CRUD operations
 Support for JPA, MongoDB, Redis, Cassandra, Elasticsearch, etc.
 Custom query generation from method names
 Paging and sorting support

2. What is Spring Data JPA?


Spring Data JPA is part of Spring Data framework that makes it easy to
implement JPA-based repositories. It simplifies interaction with relational
databases using JPA and Hibernate under the hood.
Advantages:
 Eliminates boilerplate DAO code
 Supports CRUD methods out-of-the-box
 Supports custom JPQL and native queries
 Integrates seamlessly with Spring Boot

🔍 3. Spring Data JPA – Find Records From MySQL


Example repository method to find a user by name:
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String name);
}
Usage:
List<User> users = userRepository.findByName("Asiya");

❌ 4. Spring Data JPA – Delete Records From MySQL


Spring Data JPA provides delete methods:
// Delete by entity
userRepository.delete(user);

// Delete by id
userRepository.deleteById(1L);
Custom delete query example:
@Modifying
@Query("delete from User u where u.name = ?1")
void deleteByName(String name);

5. Spring Data JPA – @Table Annotation


@Table specifies the database table that the entity maps to.
The @Entity annotation in JPA (Java Persistence API) is used to mark a Java
class as a persistent entity, meaning it can be stored in a database
Example:
@Entity
@Table(name = "users")
public class User {
// fields
}
 name: Table name
 schema: Optional schema name

📝 6. Spring Data JPA – Insert Data in MySQL Table


Saving new entity:
User user = new User();
user.setName("Asiya");
user.setEmail("[email protected]");
userRepository.save(user);
The save() method inserts the record if the ID is null.
7. Spring Data JPA – Attributes of @Column Annotation with Example
@Column maps a field to a database column and configures column properties.
Attributes:
 name — column name
 nullable — whether column can be null
 length — size for varchar
 unique — unique constraint
 insertable, updatable — control insert/update
Example:
@Column(name = "email", nullable = false, unique = true, length = 100)
private String email;

8. Spring Data JPA – @Column Annotation


Used to specify details of a column mapping in the database table.
Example:
@Column(name = "user_name")
private String username;

🔑 9. Spring Data JPA – @Id Annotation


Marks the primary key of an entity.
Example:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
 @GeneratedValue specifies auto-generation strategy (e.g., identity,
sequence)
🔗 10. How to access database using Spring Data JPA
Basic steps:
1. Create entity class with @Entity and @Table.
2. Create repository interface extending JpaRepository<Entity, ID>.
3. Autowire repository in service or controller.
4. Use repository methods (save, findById, delete, etc.) to interact with DB.
Example:
@Autowired
private UserRepository userRepository;

public User getUser(Long id) {


return userRepository.findById(id).orElse(null);
}

11. How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and
Maven?
Steps:
1. Create Spring Boot project: Use Spring Initializr or IDE.
2. Add dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
3. Configure application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/dbname
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialec
t
4. Create Entity classes with JPA annotations (@Entity, @Table, @Id)
5. Create Repository interfaces extending JpaRepository
6. Create Services and Controllers to handle business logic and HTTP
requests
7. Run the Spring Boot application

🔹 1. Spring JDBC – Definition


Spring JDBC is a module of the Spring Framework that simplifies working with
JDBC (Java Database Connectivity). It helps developers avoid boilerplate code
required for database interaction (like opening/closing connections, handling
exceptions).
it provides tools to connect Java applications to databases using JDBC (Java
Database Connectivity).
✨ It uses:
 JdbcTemplate for executing SQL queries
 Simplified exception handling
 Clean API to work with relational databases

🔹 2. Spring JDBC Template


JdbcTemplate is the core class in Spring JDBC. It simplifies common tasks such
as executing queries, inserting/updating records, and calling stored procedures.
Key Methods:
 query()
 queryForObject()
 update()
 execute()
Example:
@Autowired
JdbcTemplate jdbcTemplate;

public List<User> getUsers() {


return jdbcTemplate.query("SELECT * FROM users",
(rs, rowNum) -> new User(rs.getInt("id"), rs.getString("name")));
}

🔹 3. Spring JDBC Example


Step-by-step:
1. Add Spring JDBC and DB dependencies.
2. Configure DataSource in application.properties.
3. Autowire JdbcTemplate.
4. Write DAO/repository methods using JdbcTemplate.
public int saveUser(User user) {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
return jdbcTemplate.update(sql, user.getName(), user.getEmail());
}
🔹 4. Spring – SimpleJdbcTemplate with Example
SimpleJdbcTemplate was a convenience wrapper over JdbcTemplate that used
Java 5 features like varargs and autoboxing.
🛑 Deprecated in Spring 3.1, and its features were merged into JdbcTemplate.
Use JdbcTemplate directly instead:
jdbcTemplate.update("INSERT INTO users(name) VALUES (?)", "Asiya");

🔹 5. Spring – Prepared Statement JDBC Template


Spring JDBC supports prepared statements to prevent SQL injection and handle
parameters.
Example:
String sql = "SELECT * FROM users WHERE email = ?";
User user = jdbcTemplate.queryForObject(sql, new Object[]
{"[email protected]"},
new BeanPropertyRowMapper<>(User.class));

🔹 6. Spring – NamedParameterJdbcTemplate
Allows you to use named parameters in SQL queries for better readability.
Example:
@Autowired
NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public int saveUser(User user) {


String sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
Map<String, Object> params = new HashMap<>();
params.put("name", user.getName());
params.put("email", user.getEmail());
return namedParameterJdbcTemplate.update(sql, params);
}

🔹 7. Spring – Using SQL Scripts with Spring JDBC + JPA + HSQLDB


You can load and execute SQL scripts (for schema/data setup) automatically
using Spring + JPA with HSQLDB (in-memory DB) for testing or demos.
Add in application.properties:
spring.datasource.url=jdbc:hsqldb:mem:testdb
spring.datasource.driver-class-name=org.hsqldb.jdbcDriver
spring.datasource.username=sa
spring.datasource.password=
spring.sql.init.mode=always
spring.sql.init.schema-locations=classpath:schema.sql
spring.sql.init.data-locations=classpath:data.sql
schema.sql → Create tables
data.sql → Insert initial data

🔹 8. Spring – ResultSetExtractor
ResultSetExtractor is used for custom parsing of a result set when RowMapper
is not sufficient.
ResultSetExtractor is an interface that is used to fetch the records from the
database. It is particularly useful when we need to map an entire ResultSet
(e.g., multiple rows or complex relationships) into a single object or collection.
Example:
public class UserExtractor implements ResultSetExtractor<List<User>> {
@Override
public List<User> extractData(ResultSet rs) throws SQLException {
List<User> users = new ArrayList<>();
while (rs.next()) {
User u = new User(rs.getInt("id"), rs.getString("name"));
users.add(u);
}
return users;
}
}
Usage:
String sql = "SELECT * FROM users";
List<User> users = jdbcTemplate.query(sql, new UserExtractor());

Here is a complete and beginner-friendly explanation of all the Spring ORM


and Hibernate topics you mentioned:

🔷 1. Spring ORM – Definition


Spring ORM (Object-Relational Mapping) is a module of the Spring Framework
that simplifies the integration of ORM frameworks like Hibernate, JPA, JDO,
and iBatis into Spring-based applications.
ORM (Object-Relational Mapping) is a way to easily interact with a database
using your programming language's objects, like Java classes.
✅ Features:
 Declarative transaction management
 Easy configuration
 Integration with Spring's data access support

🔷 2. Spring Hibernate – Definition


Hibernate is a popular tool that implements ORM, essentially providing the
"bridge" between your code and the database.
Spring + Hibernate refers to integrating Hibernate (an ORM framework) with
Spring for database operations. Spring manages Hibernate's SessionFactory,
transactions, and exception translation.

3. Spring Hibernate Configuration and Create a Table in the Database


Steps:
1. Add Hibernate and MySQL dependencies.
2. Configure Hibernate in application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/dbname
spring.datasource.username=root
spring.datasource.password=pass
spring.jpa.hibernate.ddl-auto=update
3. Create entity class:
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
}
4. Run application → table created automatically.

🔍 4. JPA vs Hibernate
Feature JPA Hibernate
Type Specification Implementation
Developed By Oracle (Jakarta EE) Red Hat
Feature JPA Hibernate
Interface Standard API Specific API (Hibernate)
Usage Use via EntityManager Use via Session
Vendor-neutral Yes No (specific to Hibernate)
Hibernate implements JPA.

💡 5. Spring ORM Example using Hibernate


@Repository
public class StudentDao {
@Autowired
private SessionFactory sessionFactory;

public void saveStudent(Student student) {


Session session = sessionFactory.getCurrentSession();
session.save(student);
}
}

🔄 6. Hibernate Lifecycle
1. Transient – Object is created but not associated with any DB.
2. Persistent – Object is associated with DB session.
3. Detached – Object is disconnected from session but still exists.
4. Removed – Object is deleted from DB.

✅ 7. Spring Boot – Validation using Hibernate Validator


Hibernate Validator is the reference implementation of the Bean Validation API
(JSR 380).
public class User {
@NotBlank
private String name;

@Email
private String email;
}
Enable with @Valid:
@PostMapping("/users")
public ResponseEntity<?> saveUser(@Valid @RequestBody User user) { ... }

 🧾 8. CRUD Operations using Hibernate


Create (POST): Use session.save() to insert a new record into the
database.
 Read (GET): Use session.get() or session.load() to retrieve a record by
its primary key, or use session.createQuery() for more complex queries.
 Update (PUT): Use session.saveOrUpdate() to update an existing record
or create a new one if the key doesn't exist.
 Delete (DELETE): Use session.delete() to delete a record from the
database.

 Create:
 session.save(entity);
 Read:
 session.get(Entity.class, id);
 Update:
 session.update(entity);
 Delete:
 session.delete(entity);

🔗 9. Hibernate – One-to-One Mapping


One to one represents that a single entity is associated with a single instance
of the other entity.
@Entity
public class User {
@OneToOne(cascade = CascadeType.ALL)
private Address address;
}

🔄 10. Hibernate – Many-to-One Mapping


When a multiple class entities mapped to Single class entity is called as many-
to-one mapping.
@Entity
public class Employee {
@ManyToOne
private Department department;
}

🔁 11. Hibernate – One-to-Many Mapping


One To Many Mapping in Hibernate. In simple terms, one to many mapping
means that one row in a table can be mapped to multiple rows in another
table.
@Entity
public class Department {
@OneToMany(mappedBy = "department")
private List<Employee> employees;
}
🔃 12. Hibernate – Many-to-Many Mapping
Many-to-Many mapping is usually implemented in database using a Join
Table. For example we can have Cart and Item table and Cart_Items table for
many-to-many mapping. Every cart can have multiple items and every item
can be part of multiple carts, so we have a many to many mapping here.
@Entity
public class Student {
@ManyToMany
private Set<Course> courses;
}

💤 13. Hibernate – Eager vs Lazy Loading


 Eager: Fetches data immediately
 @OneToMany(fetch = FetchType.EAGER)
 Lazy: Fetches data only when needed (default for most collections)
 @OneToMany(fetch = FetchType.LAZY)

🧱 14. Hibernate – @Embeddable and @Embedded Annotation


The @Embeddable and @Embedded annotations in Hibernate are used to
map an object’s properties to columns in a database table.
In simple terms, @Embeddable defines a class as a reusable component that
can be embedded within other entities, while @Embedded is used to embed
that component within an entity, effectively merging its properties into the
entity's database table.
@Embeddable
public class Address {
private String city;
}
@Entity
public class Employee {
@Embedded
private Address address;
}

💾 15. Hibernate Example using JPA and MySQL


 Create entity class with JPA annotations
 Use @Repository and EntityManager
 Spring Boot auto-configures Hibernate with MySQL

🧩 16. Automatic Table Creation Using Hibernate


Set in application.properties:
spring.jpa.hibernate.ddl-auto=update
Options:
 create
 update
 validate
 none

📥 17. Hibernate – get() and load() Method


In Hibernate, both get() and load() methods are used to retrieve an object
from the database by its identifier
get() Method:
 Retrieves data immediately from the database or cache.
 Returns a fully initialized object.
 Returns null if the object is not found in the cache or database.
load() Method:
 Returns a proxy object that is lazily initialized.
 Only fetches data from the database when a property of the proxy
object is accessed.
 Throws an ObjectNotFoundException if the object is not found when a
property is accessed.

 get() – Returns null if not found (Eager loading)


 load() – Throws exception if not found (Lazy loading proxy)
session.get(User.class, 1);
session.load(User.class, 1);

📄 18. Hibernate – Pagination


Pagination is the process of dividing a large set of data into smaller, more
manageable chunks or pages for easier navigation and faster loading times.
List<User> users = session.createQuery("from User")
.setFirstResult(0)
.setMaxResults(10)
.list();

🧵 19. Hibernate – Batch Processing


In Hibernate, batch processing groups multiple related SQL statements into a
single batch and executes them with one call to the database.
Efficient way to insert/update large data in chunks:
for (int i = 0; i < users.size(); i++) {
session.save(users.get(i));
if (i % 20 == 0) {
session.flush();
session.clear();
}
}

Here is a detailed explanation of each topic related to Aspect-Oriented


Programming (AOP) in Spring and Spring Boot, including examples and
definitions:

🔸 1. Aspect-Oriented Programming and AOP in Spring Framework


AOP (Aspect-Oriented Programming) is a programming paradigm that provides
a way to separate cross-cutting concerns (like logging, security, transactions)
from business logic.( a way to handle tasks that apply to multiple parts of your
application (like logging, security checks, or transaction management) without
repeating the same code in each place)
📌 Core Concepts:
 Aspect – A module containing cross-cutting concerns
 Advice – Code to be executed (before, after, around methods)
 Join Point – A point in the program execution (like method call)
 Pointcut – Expression to match join points
 Weaving – Linking aspects with the main code

🔸 2. Spring AOP - Example (Spring 1.2 Old Style AOP)


In Spring 1.2, AOP was configured via XML.
<aop:config>
<aop:aspect ref="loggingAspect">
<aop:pointcut id="logAll" expression="execution(*
com.app.service.*.*(..))"/>
<aop:before method="logBefore" pointcut-ref="logAll"/>
</aop:aspect>
</aop:config>
Old, not commonly used today. Annotation-based is preferred.

🔸 3. Spring AOP - AspectJ XML Configuration


AspectJ is a powerful AOP framework integrated with Spring. XML-based
config:
<bean id="myAspect" class="com.app.MyAspect"/>
<aop:config>
<aop:aspect ref="myAspect">
<aop:before method="log" pointcut="execution(* com.app.service.*.*(..))"/>
</aop:aspect>
</aop:config>

🔸 4. Spring AOP – AspectJ Annotation


@AspectJ refers to a style of declaring aspects as regular Java classes
annotated with annotations.
Modern AOP is done using annotations.
@Aspect
@Component
public class LoggingAspect {

@Before("execution(* com.app.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Before method: " + joinPoint.getSignature());
}
}
🔸 5. Usage of @Before, @After, @Around, @AfterReturning, and
@AfterThrowing in a Single Spring AOP Project
 @Aspect: Marks a class as an aspect.
 @Before: Executes advice before a method execution.
 @After: Executes advice after a method execution, regardless of
success or failure.
 @AfterReturning: Executes advice only after a method returns
successfully.
 @AfterThrowing: Executes advice only after a method throws an
exception.
 @Around: Executes advice before and after a method execution,
allowing control over the execution process.
 @Pointcut: Defines a named pointcut expression that can be reused by
advice annotations.

All AOP advice types in one aspect:


@Aspect
@Component
public class AOPExample {

@Before("execution(* com.app.service.*.*(..))")
public void beforeAdvice() {}

@After("execution(* com.app.service.*.*(..))")
public void afterAdvice() {}

@Around("execution(* com.app.service.*.*(..))")
public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("Before Around");
Object result = pjp.proceed();
System.out.println("After Around");
return result;
}

@AfterReturning("execution(* com.app.service.*.*(..))")
public void afterReturningAdvice() {}

@AfterThrowing("execution(* com.app.service.*.*(..))")
public void afterThrowingAdvice() {}
}

🔸 6. How to Implement AOP in Spring Boot Application?


1. Add dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2. Use @Aspect and @Component
3. Write methods with @Before, @After, etc.

🔸 7. Spring Boot – AOP (Aspect-Oriented Programming)


In Spring Boot, AOP allows you to intercept service, repository, or controller
methods using annotations like:
 @Before
 @After
 @Around
📌 Great for logging, security, metrics, and transactions.

🔸 8. Spring Boot – Cache Provider


Caching is a technique in computing where temporary copies of frequently
accessed data are stored in a smaller, faster memory area (the cache) to
improve data retrieval speed and overall system performance.
Spring Boot's caching abstraction allows developers to use various caching
providers without changing the core application logic. This abstraction is
based on
the org.springframework.cache.CacheManager and org.springframework.cac
he.Cache interfaces.
Caching in Spring Boot improves performance.
 Spring provides annotations like @Cacheable, @CacheEvict
 Cache providers: Ehcache, Caffeine, Redis, Hazelcast
 Key aspects of spring boot cache provider
auto configuration
annotation based caching
provider selection
Enable caching:
@SpringBootApplication
@EnableCaching
public class MyApp {}
Example:
@Cacheable("users")
public User getUserById(int id) { ... }

🔸 9. Spring Boot – AOP Around Advice


@Around("execution(* com.app.service.*.*(..))")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Before method");
Object result = joinPoint.proceed();
System.out.println("After method");
return result;
}
Used for both pre- and post-processing.

🔸 10. Spring Boot – Difference Between AOP and OOP


Feature OOP AOP
Focus Code modularization by classes Code modularization by concerns
Use Case Main application logic Cross-cutting concerns like logging
Example class Car @Aspect for logging

🔸 11. Spring Boot – Difference Between AOP and AspectJ


Feature Spring AOP AspectJ
Weaving Proxy-based (runtime) Bytecode-based (compile/load-time)
Methods (Spring beans
Scope Classes, fields, constructors
only)
Performance Slightly lower Faster due to compile-time weaving

🔸 12. Spring Boot – AOP After Throwing Advice


@AfterThrowing(pointcut = "execution(* com.app.service.*.*(..))", throwing =
"ex")
public void logAfterThrowing(Exception ex) {
System.out.println("Exception occurred: " + ex.getMessage());
}
🔸 13. Spring Boot – AOP After Returning Advice
@AfterReturning(pointcut = "execution(* com.app.service.*.*(..))", returning =
"result")
public void logAfterReturning(Object result) {
System.out.println("Returned: " + result);
}

🔸 14. Spring Boot – AOP After Advice


@After("execution(* com.app.service.*.*(..))")
public void afterAdvice() {
System.out.println("After method execution");
}
Executes after the method regardless of exception.

🔸 15. Spring Boot – AOP Before Advice


@Before("execution(* com.app.service.*.*(..))")
public void beforeAdvice() {
System.out.println("Before method execution");
}

Here's a complete and easy-to-understand explanation of each topic related to


Spring Security, including definitions, usage, and examples.

🔐 1. Introduction to Spring Security and its Features


Spring Security is a powerful and highly customizable framework for securing
Java-based applications. It focuses on both authentication and authorization,
providing robust protection against common security threats. .
✅ Key Features:
 Authentication and Authorization
 Protection against CSRF, session fixation, clickjacking
 Password hashing
 Secure URLs, methods, and forms
 Integration with OAuth2, LDAP, JWT, etc.
Support for various authentication methods: Including
username/password, OAuth 2.0, and JWT.

📘 2. Some Important Terms in Spring Security


Term Description
Authentication Verifying identity of a user (e.g., login)
Authorization Granting access to resources to the user
Principal The currently authenticated user
GrantedAuthority The roles/permissions assigned
UserDetails Interface representing user info
UserDetailsService Loads user data from DB or memory

⚙️3. Spring Security Project Example using Java Configuration


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}

@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user").password("pass").roles("USER").build();
return new InMemoryUserDetailsManager(user);
}
}

🧾 4. Spring Security Form-Based Authentication


Provides a login form for users to authenticate.
 Auto-generates a login page.
 Custom form can be defined:
.formLogin()
.loginPage("/login")
.permitAll()

🔄 5. How to Change Default User and Password in Spring Security?


By default, Spring Security generates a random password.
To set custom credentials in application.properties:
spring.security.user.name=admin
spring.security.user.password=admin123
👤 6. Spring – Add User Name and Password in Spring Security
Using Java configuration:
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withUsername("john")
.password("{noop}1234")
.roles("USER").build();
return new InMemoryUserDetailsManager(user);
}
{noop} = No password encoding (for testing only)

🔑 7. Spring – Add Roles in Spring Security


Assign roles during user creation:
User.withUsername("admin").password("{noop}pass").roles("ADMIN", "USER")
Check roles in code:
@PreAuthorize("hasRole('ADMIN')")

8. Spring Security JSP Tag Library


To secure JSP pages using tags:
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"
%>

<sec:authorize access="hasRole('ROLE_ADMIN')">
<p>Admin content here</p>
</sec:authorize>

🔁 9. Spring Security – Remember Me


Allows users to stay logged in even after browser restarts.
.and()
.rememberMe()
.tokenValiditySeconds(86400) // 1 day
.key("mySecret")

🧩 10. Spring Security XML


Older configuration style using XML instead of Java classes:
<http auto-config="true">
<intercept-url pattern="/admin/**" access="ROLE_ADMIN"/>
<form-login login-page="/login"/>
</http>

<authentication-manager>
<authentication-provider>
<user-service>
<user name="user" password="pass" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>

🔐 11. Spring Security at Method Level


Enable with:
@EnableGlobalMethodSecurity(prePostEnabled = true)
Use in controller/service:
@PreAuthorize("hasRole('ADMIN')")
public String secureMethod() { ... }
Other annotations:
 @Secured("ROLE_USER")
 @PostAuthorize(...)

🌐 12. OAuth2 Authentication with Spring and GitHub


1.OAuth2 allows users to log in with third-party providers (e.g., GitHub,
Google).
2.JWT (JSON Web Token) with Spring Security is a method for securing Spring
applications using token-based authentication. It's a stateless approach,
meaning the server doesn't need to store session information, making it
suitable for microservices and distributed systems.
Example with GitHub:
spring.security.oauth2.client.registration.github.client-id=XXX
spring.security.oauth2.client.registration.github.client-secret=YYY
 Add dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
 Spring Boot auto-configures GitHub login at /login/oauth2/code/github.

You might also like