Presentation1.pptx
Presentation1.pptx
• Spring Framework is a Java platform that provides comprehensive infrastructure support for
developing Java applications. Spring handles the infrastructure so you can focus on your
application.
• Spring is an open-source framework which can be used for developing server side
application as well as monolithic application
• Spring framework is dedicated for java
• It provides more flexibility as springmvc is entirely based on interfaces
• Unlike structs and hibernate so we can easily make required changes in implementation
without affecting the client side
Features of Spring Framework
Open Source framework
Light weight application
Reduces the overall complexity
Comprehensive tool
Spring framework avails an array of resources
Ioc is possible becoz of loosely coupling, modular design testability
Backend Server side Client Side Front-End
logic/Applicati app’n app’n logic/
on Application
Monolithic Application
Server side application are the application that contains only the backend logic for the
application
In this case the server and client side application are developed built and deployed
independently
The monolithic application are the application are the application that contain both backend
and frontend logic
In this case the backend and frontend logic are develop built and deployed as one single
application
Spring architecture
ORM WEB
AOP MVC
DAO CONTEXT
CORE
The Spring Framework consists of the following modules. These modules are Spring Core, Spring AOP, Spring Web MVC, Sprin
DAO, Spring ORM, Spring context, and Spring Web Flow.
ORM module
AOP provides (Aspect The Web module Spring DAO modules
provides
oriented have provided a set
programming) integration layers provides basic
web-oriented of predefined
implementation for popular
integration features classes and
allowing you to define object-relational
method-interceptors such as initialization interfaces to provide
and pointcuts to
mapping APIs, DAO support in the
of the IoC container
cleanly decouple including JPA, form of
using servlet listeners
code that implements JDO, Hibernate, “org.springframewor
functionality that
and a web-oriented k.dao” package.
and iBatis. application context.
should be separated.
The Context module
builds on the solid base
provided by the Core
and Beans modules and Features of
it is a medium to access
SPRING spring
any objects defined and CORE framework
configured. The
ApplicationContext
interface is the focal
point of the Context
module.
SPRING Monolithic
MVC application
The Core module
provides the
fundamental parts
of the framework,
including the IoC SPRING
and Dependency REST Restful API’S
Injection features.
The Web-MVC
module
contains Spring's SPRING Microservices/
Model-View-Co BOOT WebServices
ntroller (MVC)
implementation
for web
applications.
1) Spring Core
There are two key features in spring core
I) IOC (inversion of control)
II) DI (Dependency Injection)
a) IOC :
• IOC stands for inversion of control.
• This feature represents that the control over object creation will be inverted in the spring framework.
• It means the programmer will no longer be responsible to create an object.
• It spring container/IOC container is component responsible for creating an object, managing its life
cycle and then destroying that object.
• The objects in spring framework are light-weight object and are known as Beans.
• Ioc means object creation control on spring . Spring works directly create runtime object and inject
using IOC.
• The spring container takes help of “BeanFactory” to create the beans requested by the programmer.
• BeanFactory creates the beans based on the BeanConfiguration provided by the programmer.
a.1] BeanConfiguration:
The process providing the values for the beans that will be created by the sprig beans that will
be created by the spring beans that will be created by the spring container is known as Bean
Configuration.
bean configuration can be done in 2 ways :
a.1.1] XML Configuration
a.1.2] Annotation Configuration
IOC CONTAINER FEATURES
Spring IOC
Framework
Managing their
Configuring
complete life cycle
Types of Ioc Container
IOC
• The process of injecting the bean of the dependency class into the bean of dependent class is
known as Dependency Injection.
• The class which depends on another class object for its own object creation is known as a
“Dependant class”.
• The class on which the dependent class depends upon is called as “Dependency Class”.
• DI makes our programming code loosely coupled, which means change in implementation doesn’t
affect the user.
Benefits of DI :
• A basic benefit of dependency injection is decreased coupling between classes and their
dependencies
• Reduced coupling between the parts of an application.
• Increased cohesion of the parts of an application.
• Increased test-ability
• Better design of applications when using dependency injection
• Increased re-usability.
• Standardizes parts of application development.
• Increased maintainability.
• Reduces boilerplate code
Two ways to inject dependency :
a) By Constructor : The <constructor-arg> sub element of <bean> as used for constructor injection.
Constructor injection, where dependencies are provided through a client's class constructor.
b)Setter injection, where the client exposes a setter method which accepts the dependency. The
<property> subelement of <bean> is used for setter injection.
Class student{
Id, name, address;
setId(id){}
setName(name){}
setAddress(address){} Ioc container
}
object
Class address{
Street, city, state, country
setStreet(street);
setState(state);
setCountry(country);
}
Class Address{
String street, city, state, country;
Address(street,city,state,country)
{
}
}
Address
Class student{
String Id, name, address;
Student(id,name,address){
}
} object
id,name,address
Bean Life Cycle
Container is shutdown
Call disposable
Call Custom destroy
destroy()
• Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring
container gets started. After that, the container creates the instance of a bean as per the request, and then
dependencies are injected. And finally, the bean is destroyed when the spring container is closed.
• Therefore, if we want to execute some code on the bean instantiation and just after closing the spring
container, then we can write that code inside the custom init() method and the destroy() method.
• Three approaches to implement the life cycle of bean
1)using xml
2)using programmatic approach
3)using annotations
ApplicationContext in spring
• Spring IoC container is responsible for instantiating, wiring, configuring, and managing the entire life
cycle of objects.
• BeanFactory and ApplicationContext represent the Spring IoC Containers. ApplicationContext is the
sub-interface of BeanFactory.
• BeanFactory provides basic functionalities and is recommended to use for lightweight applications
like mobile and applets.
• ApplicationContext provides basic features in addition to enterprise-specific functionalities which
are as follows:
1. Publishing events to registered listeners by resolving property files.
2. Methods for accessing application components.
3. Supports Internationalization.
4. Loading File resources in a generic fashion.
BeanFactory in spring
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. BeanFactory uses Beans and their dependencies metadata to create and configure them
at run-time.
BeanFactory loads the bean definitions and dependency amongst the beans based on a configuration file(XML) or
the beans can be directly returned when required using Java Configuration.
Annotations in spring
@Bean : This annotation used to mark the BeanConfiguration of a specific class. It can be used at the
method level to indicate that the method level to indicate that the method is providing the values of the
properties for the required class object.
@Component : This annotation is used to mark a class for being considered for the process & bean creation. It means if a
class is annotated as @component then the springframework considers that class eligible for beancreation. If a class is not
annotated as @component then the spring container will not create bean(objects) for such class.
@componentScan : This annotation is used to scan the mentioned packages for the classes annotated as @ component.
It means while configuring a bean of a certain class , we need to mentioned the packages of that class so that the component
scan annotation can verify(scan) for the annotation @component for the class
@Value: This annotation is used to provides the value of the properties at the declaration.
@AllArgsConstructor: To obtain the all argumented constructor through Lombok we can make use of
@AllArgsConstructor
@NoArgsConstructor: To obtain the no argumented constructor from Lombok we can make use of @AllArgsConstructor
SPRING MVC
• In spring framework the mvc module is used to developed monolithic
applications(web Application).
• A Spring MVC is sub framework of spring framework which is used to build a
web-application.
• It is build on Servlet – API.
• It means a spring MVC application will consist of both, the front end and the back
end logic.
• MVC stands for Model-View-Controller
• Model means data
• View means presentation logic
• Control means control (using servlet) interface between model and view
• It implements all the basic feature of a core spring framework like Ioc, DI
• MVC is one of the architectural design pattern
• Powerful configuration(xml, annotation)
• It is way to organize the code in our application
Model View Controller Architecture
st Dispatcher- Controller
que
Web-re servlet Service Repository Pojo
Client
Web
-res
View-
ponse view Resolver
DB
1. The client will send a web-request which will received by the dispatcher-servlet
component
2. The dispatcher-servlet will take help of the Handler – Mapping component to
identify the controller which is responsible to handle that particular request.
3. The controller will decide which service logic has to be implemented
4. The service layer is responsible to perform validation on incoming and outgoing
data
5. The service will decide which logic from repository should be implemented
6. The repository layer is responsible to perform execution logic (CRUD operations) on
the application entities. It means we will perform operations on the POJO in the
repository layer
7. The pojo layer is responsible to hold the entity classes require for the application
8. Pojo stands for plain old java object
9. Once the models data is written from service to controller, the controller takes help
of view resolver component to identify and locate the required view page
10. The model data is then arrange in the view page which is given as the
web-response.
Dispatcher-servlet
The layers controller, service,
The ds has to be configure in web-xml
repository, pojo are represented as
file which is known as the
packages and annotated with
deployment-descriptor. The ds will be
@controller, @service, @repository,
used to configure handler mapping and
@entity respectively
view resolver component
• Request Mapping Methods
The doGet() and doPost() methods are mapped in springMVC in the form of annotations.
In order to mapped this methods from the request to a specific controller we can make used of
following annotations.
❖ @RequestMapping : it is a generic mapping method which can be used to mapped any
mapping method to the controller. It can be done with the help of the “method attribute”.
❖ @GetMapping: It is used to map only ‘Get’ method from the request to the controller
❖ @PostMapping: It is used to map only ‘Post’ method from the request to the controller
The url pattern followed by the request is declared as a string value. In the path attribute in each
of the annotations.
@ModelMap
The object of this class is an implicit object It helps us to map the model attribute to the view
pages. (model means repository, service, pojo) the object of this class helps us to send some data
from the controller(backend) to the view pages (frontend). It is done with the help of
‘addAttribute()’. To fetch the attribute in the view page we need to use a method called
‘getAttribute()’ which is present in HttpRequest
Spring with JDBC
Spring jdbc is powerful mechanism to connect to the JDBC and execute SQL
queries.
Data Interface
source interface file
file
Jdbc template Implements Datasource
DriverManager Datasource
Queries – fire, driverClassName = ? url =
insert,delete ? Password = ?
,update ,select Username=?
Class file
• Selecting data using spring jdbc
1. public T queryForObject (String sql, Rowmapped <T> rowMapper, objects args) it is return single object.
2. Public List <T> query (String sql, RowMapper <T> rowMapper) it is returns the list of objects or
multiple objects.
Implementation of
rowMapper
program orm DB
Class ABC{
String name; DB
orm
String college;
} name college
How to work with spring orm
Interface
Local session
datasource
factory
Database properties,
url, username, pwd
1. Datasource
2. Hibernate properties
3. Annotated class
AOP
Aop stands for Aspect Oriented Programming. In spring is a programming
paradigm used to modularize cross-cutting concerns in your application. It helps
you separate and manage aspects like logging, security, and transactions which
often affect multiple parts of your codebase.
In spring, AOP is implemented usings aspects, advice, pointcuts, and join points.
@Aspect: This annotation is used to define a class as an aspect. It identifies a class that contains advice and pointcut definitions. Aspects are
usually annotated with @Aspect.
@Before: This annotation is used to mark a method as "before" advice. The annotated method will run before the join point specified in the
pointcut expression.
@After: Marks a method as "after" advice. It runs after the join point execution, regardless of the outcome (success or exception).
@AfterReturning: This annotation is used for "after returning" advice, which executes after the successful execution of a method.
@AfterThrowing: Marks a method as "after throwing" advice, which executes after a method throws an exception.
@Around: Used to create "around" advice, allowing you to control the join point's execution by proceeding or aborting it within the annotated
method.
@Pointcut: This annotation defines a reusable pointcut expression, which can be referenced in advice methods. It helps in avoiding
redundancy by defining the same pointcut in multiple places.
@Order: Specifies the execution order of aspects when multiple aspects are applied. Lower values indicate higher precedence.
@EnableAspectJAutoProxy: This annotation is placed on the configuration class to enable AOP support in Spring. It allows Spring to create
proxy objects for the advised beans.
AOP Example
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before; @Servicepublic
class MyService { public void doSomething() { @Servicepublic class MyService
System.out.println("Service method executed."); }} {
@Aspectpublic public void doSomething()
class LoggingAspect { {
@Before("execution(* com.example.service..(..))") System.out.println("Service method executed.");
public void beforeServiceMethodExecution() }
{ }
System.out.println("Before executing a service method.");
} @Configuration
} @EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.example")
public class Main public class AppConfig {
{ }
public static void main(String[] args) {
ApplicationContext context = new In this example, the LoggingAspect class defines the aspect, which logs
AnnotationConfigApplicationContext(AppConfig.class); a message before the execution of any method in the
MyService service = context.getBean(MyService.class); com.example.service package. The @EnableAspectJAutoProxy
service.doSomething(); annotation in the configuration class enables AOP support. When you
} run the Main class, you'll see the "Before executing a service method"
} message before the "Service method executed" message, demonstrating
the AOP aspect's action.