leat eee
Koo) Fe
reey.\\- wae
Unit- 5 ONE SH©
ae or a J
By: Vikas Sir(Spring Framework & Spring Boo
Syllabus:
¢ Spring Framework: Spring Core Basics-Spring Dependency Injectio
concepts, Spring Inversion of Control, AOP, E Bean Scopes: Singleton, leton,
Prototype, Request, Session, Application, Web Socket, Auto wiring,
Annotations, Life Cycle Call backs, Bean Configuration styles.
2s Boot: Spring Boot Build Systems, Spring Boot Code Structure,
Spring Boot Runners, Logger, BUILDING RESTFUL WEB SERVICES, Rest
Controller, Request Mapping, Request Body, Path Variable, Request
Parameter, GET, POST, PUT, DELETE APIs, Build Web Applications.Java Programming by VikasSir
Spring Core Basic:
* Spring Core is the fundamental part of th¢Spring Framework] which
provides the basic functionalities of dependency injection (Dl) and
inversion of control (IoC).
* These principles are the foundation for oretyinaonsely co coupled] modular
applications in Java.
* Spring Core is(composed of several modules] but the most critical ones
are:
Core Container: This includes the core, beans, context, and expression
language modules~
_2 ore and Beans: Provides the/fundamental parts of the framework
including loC and dependency injection features.
eeeJava Programming by VikasSir
* Dependency Injection (Dl): At the heart ofSpring Cordis the idea of DI,
where objects define their dependencies, and the container injects these
dependencies at runtime.
* Inversion of Control (IoC): IoC is a principle where the.cantrol of object
creation and management is inverted.
pains Framework:
* The Spring Framework is 4 popular tool in Java for building applications,
especially those that are large am lex.
* It provides a set of features and toolsithat make iteasier to develop,
_Manage, and maintain Java applications.
=Java Programming by Vikas Sir
Features of Spring Framework:
* Inversion of Control (loC): Spring's loC container manages the life cycle|and
Configuration of application objects. It helps in creating loosel eovet
applications. . Bo
. Dependency Injection (Dl): Spring enables you to inject dependencies into
objects rather than letting the objects manage their dependencies
themselves, which promotes decoupling and easier testing.
<2-*Spect-Oriented Programming(AOP)>Spring AOP allows youto define _
cross-cutting concerns, like logging, security, and transaction management,
separately from the application's business logic.
_2-7fansaction Management: Spring provides jistent and flexible
transaction management abstraction that can work with various transaction
management APIs like JDBC, JTA.Java Programming by VikasSir
+ Spring Security: Spring Security is a Gmprehensive security framework]
that provides authentication, authorization, and other security features for
Java applications.
+-tightweight and Portable: Despite its comprehensive feature set] Spring is
designed to be lightweight, making it easy to integrate into different
environments. It is also portable across different tforms and application
servers. 4
_» Spring Test Framework: Spring provides {robust test framework that
supports unit testing, integration testing, and testing of web applications. It
integrates well with popular testing frameworks likeJUnitjand TestNG]Spring Dependency Injectio:
+ Dependency Injection is the main functionality provided by Spring _
10CUnversion of Control).
+ The pring-Core moduls is responsible foKinjecting dependencies ?
through either Constructor or Setter methods.
wr
* The design principle of Inversion of Control emphasizes keeping the
Java classes independent of each other 4nd the container frees them
from object creation and maintenance.
« These classes/ imanagtt by Spring] must adhere to the standard
definition of Java-Bean
* Dependency Injection in Spring also ensureg loose coupling between
the classes.Spring Dependency Injection Figure :Spring Dependency Injection Example :
lass Engine {
A public void start() {
AA System.out.printin("Engine startet
By
Clase
Zs oak AV aniable.
‘/\ private Engine engine;
// Engine is injected into the Car class through the(constructor |
public Saenger) t
ates = ehgine;
public void startCar() {
engine.start();public class Main {
ublic static void main(String[] args) {
// Creating an instance of Engine
Engine engine =ewEngine();
// Injecting the Engine instance into the Car class
Fas = new Car(engine);
}
}
caf.startCar();
OUTPUY: Engine started_Java Programming by VikasSir
Types of Spring Dependency Injection:
1. Constructor Injection:
* Dependencies are provided through the class’{ constructor] When you
create an object of that class, you pass the dgpendenciesjto the
constructor.
* It makes sure that the object is created with all its necessary
dependencies.
en Injection:
© What It Is: Dependencies are provided through setter methods,|which are
methods that allow you to Set" the value bf a property after the object is
created.
* Itgives morg Reb os you car(create the object/first and then set its
dependencies.Advantages of Spring Dependency Injection:
* Promotes Reusability
* Increased Testability
_2 Configuration Management
_2 Flexibility
* Support for Different Environments
« Improved
SJava Programming by VikasSir
Inversion of Control (loC):
* Inversion of Control (loC) container isa framework that uses automated
dependency injection (DI) to manage components of an application.
© The loC container is the core of thd Spring framework and is represented
by the ApplicationContext interfac
The loC container's responsibilities :
Aerating objects: The loC container create objects, alse{known as beans.)
2 Sorifiguring and assembling dependencies: The loC container uses
configuration files, annotations, and Java code to define dependencies
between objects.
* Managing the life cycle of objects: The loC container manages the entire
life cycle of objects.Java Programming by VikasSir
= Cesses (PO!)
SS contgureion
Siete
Produces ae
figured sytem
ae
, Benefits of loC:
(2-£66se coupling: Your objects are less@ependent on each other} making your code
more flexible and easier to maintain.
_2 £4Sier testing: You can easily replace dependencies with/mock objects/during
testing.
_= simplified development: You don't have to worry about creating and managin
objects, which allows you to focus on chqousinessiogiel id managingAspect-Oriented Programming (AOP):
* Aspect-Oriented Programming (AOP) in Spring is
that helps you separate cross-cutting concerns (like logging, security,
transaction management) from the main business logic.
+ AOP allows you to ade{additional behaviorito your code without modifying
TLoggin
a
AOP [Security]
Module 1 Module 2 Module 3Java Programming by VikasSir
ey Concepts in AOP:
* Aspect: A module that encapsulates cross-cutting concern.|in Spring, an
aspect can be a class annotated witli@Aspect.| _
Join Point: A point during the execution of a program, such as the execution
of a method or the handling of an exception.
* Advice: The action taken by an aspect at a(particular join point, Different
types of advice include @Before, @After, @Around, @AfterReturning, and
@AfterThrowing._
<2 Potntcut: A predicate that{matches join poi | Advice is associated with a
pointcut expression andruns at any join boint matched by the pointcut.
Defines a Spring bean.
id: Unique identifier for the bean.
class; Fully qualified class
* Inject Dependencies: | ap
_sbean id="beanName" class="fully.qualified.ClassName">
+ name:The name of the(property to be injected.
* ref: References another beai
Java Programming by VikasSirJava Programming by Vikas Sir
(2). Java Based Cor
* Java-based configuration, also known as JavaConfig,jallows you to
configure beans(using Java classes] You use annotations a1 acode to
define beans, dependencies, and configurati ee
imple:
//Java-based configuration
_-— @Configuration / >
public class AppConfigt
@Bean //< C SBrim 9 Bean define )
public MyBean myBean() {
MyBean bean Eney MyBean();
co
bean.setName'
return bean;
h(3). Annotation Based Configuration:
* Spring annotation-based configuration uses annotations onclass,
method, or field declarations to operate on metadata in the component
class. Here are some annotations that you can use in Spring annotation-
based configuration: ~
@Configuration
© This annotation indicates that a class is source of bean definitions. /
@Bean
* This annotation indicates that a methodforoduces a bedn that the Spring
georieaines will marge
@SpringBootApplication
* This anion gn almsne Spring see cation conviguration and allows you
to.custamize and modify application properties.(Example:
//Annotation-Based Configuration
@component
public class MyBean
[
@value(“ankit”); =>
private String name; // Bean method,lifecycle hooks,etc.
}
r Java configuration with component scanning:
* Java configuration with component scanning in Spring allows you to define your
beans and their dependencies using,
+ The @ComponentScan annotation is used to tell Spring which packages to scan
for components (classes annotated with @Component, @Service, @Repository;
@Controller, etc.).definiti
@ComponentScan: This annotation tells Spring to scan the specified
package(s) for components.
basePackages: This attributespecifies the package(s) ko scan for
components.
Example: //java configuration with component scanning
=> @Configuration vy |
Cami nantagn besser icee-"com example)
public class AppCongif{
//No Explicit bean definitionneeded
}
@Configuration: This annotation marks the class as a source of bean
Tatton marks te class as a sourceomean
S_Java Programming by Vikas Sir
(5).XML Configuration with Component Scanning:
* In Spring Framework, you can use XML configuration to-define a component
scan na Configuration fla This tells Spring to search for-classesina_
_specified package that are annotated with @Named or @Component.
* To define a component scan using(XML configuration, you can use the
tag. This tag specifies the base package for the
component scan.
* you can use the following XML configuration to define two beans and
specify constructor injection: —
* sbean name: ‘io.datajek.spring.MyDependency”
* a
* Java Programming by VikasSir
Spring Boot Build System:
* In(Spring Boot choosing adsuild system is aar(important task. So, javen pr
Gradle are good build system as they provide a good support for _
dependency management.
* Spring Boot team provides a list of dependencie:
version for its every release _
* You do not need to provide a version for dependencies in the build _
configuration file Spring Boot automatically configures the dependencies
version based on the release.
* When you upgrade thefSpring Boot versio, dependencieg will upgrade
automaticallyJava Programming by VikasSir
Maven Build Tool:
* Maven is a popular.open-source build tool that helps developers-build,
publish, and deploy projects.
It's written in Java and can be used fo(Brojects in Javaio#
pier languages.
* Maven is based on the Project Object Model(om) pnd aims to simplify
and standardize the build process.
a aw *
Ruby, and
Maven helps developers by:
* Automating sourcecode compilation bn dependency management
* Assembling binary codes into packages
xecuting test scriptsDeploy
Teper” eeu
FackagJava Programming by VikasSir
Maven Dependency::
* Maven configuration, we should inherit the Spring Boot Starter parent
project to manage the Spring Boot Starters dependencies. For this, simply
we can inherit the starter parent in ous pom.xml file as shown below.
ape C Pom )
org,springframework,boot
spring-boot-starter-parent
1.5.8.RELEASE
> lparent>
—sytependency>
_sgroupid>org.springframework.bgot
spring-boot-starter-web
_Java Programming by VikasSir
iradle Build Tool:
* Gradle is another build tool like Maven, but it’s designed to be more flexible
and faster, often used for Java projects but also supports other languages
like Kotlin;Groovy, and more.
* InGradle, the build process | . Each task is a piece of
work that Gradle needs to do, like compiling code or running tests.
* You declare the libraries and frameworks your project needs in the
build.gradle file, and Gradle will download them and make them available in
ry
your project.
Gradle Build Tool Dependency:
* We can import the Spring Boot Starters dependencies directly into
build.gradle file. We do not need Spring Boot start Parent deparidency lke
Maven or Gradle.Gradle Build Tool Dependency:
Buildscript {
ext{
springBoot Versi
2
repositories {
_MavenCentral() _
}
pendencies {
classpath(“or,
{springBoot Version}”)