Java Web Framework - Spring

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 52

Java Web Framework

1. Spring MVC
2. Overview of Spring
3. Spring Architecture
4. bean life cycle,
5. XML Configuration on Spring,
6. Aspect Oriented Programming (AOP)with
Spring,
7. Managing Database and Managing
Transaction.
Java Web Framework

• A Java framework is the body of predefined codes used by


programmers to develop applications on the web.
• These Java frameworks are classes and functions that control
hardware, process input and communicate with system applications.
• Java frameworks contain pre-written codes and libraries that help
the developer build an application without writing all the code
individually.
• Java frameworks are also called libraries and APIs.
Java Web Framework

• Java frameworks help to provide structure when


developing applications.
• The development of frameworks for testing, online
applications, and ORM (object-relational mapping) is
one way that programmers can automate various tasks
and produce reliable outcomes.
Top 10 Java Web Framework
Spring Framework

• Spring is an open-source lightweight Java web development


framework used to build fast, flexible, and portable apps and
systems.
• It provides infrastructure support to develop Java
applications.
• Using the Spring web framework, developers can build goal-
oriented Spring web applications using Plain old Java
objects.
Overview of Spring Framework

• Spring makes it easy to create Java enterprise applications.


• The term "Spring" means different things in different contexts.
• Spring came into being in 2003 as a response to the complexity of
the early J2EE specifications.
• It provides everything developer need to embrace the Java
language in an enterprise environment.
• It support for Groovy and Kotlin as alternative languages on the
JVM.
• It provides flexibility to create many kinds of architectures
depending on an application’s needs.
• As of Spring Framework 6.0, Spring requires Java 17+.
Overview of Spring Framework

Advantages of Spring
• User can use Spring for application testing alongside the
backward compatibility.
• Java Spring framework helps to establish JDBC connections.
• These frameworks are compatible with XML configurations.
• It helps to fire up web apps without any actual web server.
Overview of Spring Framework

Features:
• Core technologies: dependency injection, events, resources, i18n,
validation, data binding, type conversion, SpEL, AOP.
• Testing: mock objects, TestContext framework, Spring MVC Test,
WebTestClient.
• Data Access: transactions, DAO support, JDBC, ORM, Marshalling XML.
• Spring MVC and Spring WebFlux web frameworks.
• Integration: remoting, JMS, JCA, JMX, email, tasks, scheduling, cache and
observability.
• Languages: Kotlin, Groovy, dynamic languages.
Overview of Spring Framework

•Spring Boot is an extension of Spring Framework. Whereas Spring MVC is a


subframe of Spring FrameWork.
• What is the Difference Between Spring MVC and Spring Boot?
•Spring MVC is a Model-View-Controller-based web framework widely used

to develop web applications.


•Spring Boot is an enhancement of the Spring framework, with some
extended advantages, widely used to develop REST APIs.
REST stands for Representational State Transfer and was created by computer scientist
Roy Fielding & a group of developers decided to create a standard so that any server could
talk to any other server. He defined REST. REST's universal rules make it easier for
Spring Architecture
•The Spring Framework consists of features organized into number of modules.
•These modules are grouped into Core Container, Data Access/Integration, Web,
AOP (Aspect Oriented Programming), Instrumentation, and Test
Spring Architecture
Core Container:
• Core Container consists of the Core, Beans, Context, and Expression
Language modules.
• Core Container provides the fundamental functionalities of the Spring
framework including Dependency Injection (DI) and Inversion of
Control (IoC) thorugh Core and Bean modules.
• The Context module inherits its features from the Beans module and
adds support for internationalization (using, for example, resource
bundles), event-propagation, resource-loading, and the transparent
creation of contexts by.
• The Expression Language module provides a powerful expression
language for querying and manipulating an object graph at runtime.
Spring Architecture
Spring Web:
• Web facilitates the development of powerful and scalable web
applications in Java.
• servlet is a fundamental component that plays a crucial role in handling
web requests and generating responses. Servlets are Java components
that extend the functionality of a web server, allowing developers to
handle requests, generate dynamic web content, and manage sessions.
• The Web-Struts module contains the support classes for integrating a
classic Struts web tier within a Spring application.
• The Web-Portlet module provides the MVC implementation to be used
in a portlet environment and mirrors the functionality of Web-Servlet
module.
Spring Architecture

Data Access/Integration:
• Spring Data Access comprises a collection of modules designed
for efficiently accessing data stored in diverse formats such as
databases, messaging systems, and XML.
• These modules that simplify data retrieval and manipulation
within the Spring framework.
• JDBC: Streamlines the process of accessing databases
• ORM: ORM frameworks map data to Java objects on a field-by-field basis.
• Java Messaging Service (JMS) module makes it easier to implement messaging
communication within the Spring framework.
• OXM specifies a way of transferring and accessing data in XML format.
• The Transactions Management API establishes a unified approach to handling
transactions for both data objects and databases
Spring Architecture
AOP, Aspects and Instrumentation:
• AOP stands as an implementation of Aspect-Oriented
Programming, simplifying the handling of secondary tasks in
Java objects.
• Objects in Java often have primary responsibilities, but they may
also need to perform secondary tasks like logging or exception
handling.
• Aspect-oriented programming enables the extraction of these
secondary responsibilities from objects.
• The Instrumentation module offers essential support for class
instrumentation, a crucial aspect of monitoring an application’s
performance.
Spring Architecture

Test:
• The Test module supports the testing of Spring components with
JUnit or TestNG.
• It provides consistent loading of Spring ApplicationContexts and
caching of those contexts.
• It also provides mock objects that you can use to test your code
in isolation.
Spring MVC

• Spring Web MVC is the original web framework built on the


Servlet API and has been included in the Spring Framework
from the very beginning.
• Spring MVC is mostly used for developing web applications.
• It follows the MVC (Model-View-Controller) Design Pattern
which works around the Front Controller i.e. the Dispatcher
Servlet.
• This design pattern specifies that an application consists of a
data model, presentation information, and control information.
Spring MVC

• Spring MVC implements all the basic features of a core spring


framework like Inversion of Control, Dependency Injection.
• This framework is developed around a DispatcherServlet which
dispatches requests to handlers.
• Parallel to Spring Web MVC, Spring Framework 5.0 introduced a
reactive-stack web framework whose name, "Spring WebFlux".
• The Dispatcher Servlet handles and dispatches all the incoming
HTTP requests to the appropriate controller.
Spring MVC
• Dispatcher Servlet uses @Controller and @RequestMapping as default
request handlers.
• The @Controller annotation defines that a particular class is a controller.
• @RequestMapping annotation maps web requests to Spring Controller
methods.
• The terms model, view, and controller are as follows:
• Model: The Model encapsulates the application data.
• View: View renders the model data and generates HTML output that the
client’s browser can interpret.
• Controller: The Controller processes the user requests and passes them to
the view for rendering.
Spring MVC
• Dispatcher Servlet uses @Controller and @RequestMapping as default
request handlers.
• The @Controller annotation defines that a particular class is a controller.
• @RequestMapping annotation maps web requests to Spring Controller
methods.
The terms model, view, and controller are as follows:
• Model - A model contains the data of the application. A data can be a single
object or a collection of objects.
• Controller - A controller contains the business logic of an application,
processes it and sents it to the View for rendering. Here, the @Controller
annotation is used to mark the class as the controller.
Spring Model-View-Controller

•View - A view represents the provided information and generates HTML


output that the client’s browser can interpret.
• JSP+JSTL is used to create a view page.
• [Although spring also supports other view technologies such as Apache
Velocity, Thymeleaf and FreeMarker.]
• Front Controller - In Spring Web MVC, the DispatcherServlet class
works as the front controller. It is responsible to manage the flow of the
Spring MVC application.
Spring Model-View-Controller

The Flow of Spring MVC:


Spring Model-View-Controller

The Flow of Spring MVC:


• All the incoming request is handled by the DispatcherServlet that
works as the front controller.
• The DispatcherServlet gets an entry of handler mapping from the
XML file( or through Web Annotations) and forwards the request
to the controller.
• The controller returns an object of ModelAndView.
• The DispatcherServlet checks the entry of view resolver in the
XML file and invokes the specified view component.
Bean Life Cycle

•A Spring bean is a Java object managed by the Spring IoC container.


•These objects can be anything, from simple data holders to complex
business logic components.
•The bean life cycle refers to when & how the bean is instantiated,
what action it performs until it lives, and when & how it is destroyed.
•The bean life cycle empowers developers to effectively manage
resources, configure beans, and ensure proper initialization and
cleanup.
•It improves application’s performance, prevent memory leaks, and
• implement custom logic at various stages of a bean’s existence
Bean Life Cycle
Figure: Spring Bean Life Cycle
Bean Life Cycle

• This life cycle encompasses several stages, starting with the creation of
a bean, followed by its initialization, use during the application's
runtime, and finally, its destruction.
• Managed by the Spring IoC container, this process offers developers
the opportunity to inject custom behavior at different phases.
• When a Spring Container creates a bean, it provides two methods to
every bean by default. These are:
1) public void init() 2) public void destroy()
• The init() method is called after bean construction and before
requesting an object.
• destroy() method is called just before the destruction of a bean.
Bean Life Cycle

• init(): If derveloper want to initialize anything such as loading some


configurations, creating database connections, can write that code in
init() method.
• destroy(): If developer want to cleanup something such as closing
database connections, releasing the used resources, can write that code
in destroy() method.
• There are three approaches to configure Spring Bean Life Cycle
methods:
1) Using XML (also called Declarative Approach)
2) Using Spring Interfaces (also called Programmatic Approach)
3) Using Annotations
Bean Life Cycle
Spring Bean life cycle stages:
Bean Life Cycle

Spring Bean life cycle stages:


1. Instantiation: Setting the Foundation
• During this stage, the container creates a new instance of the bean by invoking its
constructor.
• The primary purpose of this stage is to Initialize essential properties and resource.
eg:
public class Character {
public Character() {
System.out.println("Instantiation: A new character has been created.");
}
// Other methods
}
Bean Life Cycle
Spring Bean life cycle stages:
2. Population of Properties: Filling the Gaps
• At this stage,the Spring container injects properties and dependencies into the bean.
• Then Configure the bean with the required resources.
eg:
public class Character {
private Weapon weapon;
private Item item;

public void setWeapon(Weapon weapon) {


this.weapon = weapon;
System.out.println("Population of Properties: Equipping " + weapon.getName() + " to " + getName());
}
public void setItem(Item item) {
this.item = item;
System.out.println("Population of Properties: Adding " + item.getName() + " to " + getName() + "'s
inventory");
}
// Other methods
}
Bean Life Cycle

Spring Bean life cycle stages:


3. BeanNameAware: Giving Identity
• After instantiation, this stage makes beans to know their assigned name and
access the name assigned to the bean.
eg:
public class Character implements BeanNameAware {
@Override
public void setBeanName(String name) {
System.out.println("BeanNameAware: Setting bean name: " + name);
}
// Other methods
}
Bean Life Cycle
Spring Bean life cycle stages:
4. BeanFactoryAware and ApplicationContextAware: Embracing Context
• In this stage beans gains access the broader application context and Interact with
other beans and resources.
eg:
public class Character implements BeanFactoryAware, ApplicationContextAware {
@Override
public void setBeanFactory(BeanFactory beanFactory) {
System.out.println("BeanFactoryAware: Setting bean factory");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
System.out.println("ApplicationContextAware: Setting application context.");
}
// Other methods
}
Bean Life Cycle
Spring Bean life cycle stages:
5. BeanPostProcessor: Adding Magic
• During this phase, custom logic can be executed before and after the bean’s initialization. It allows for additional
actions and transformations during bean creation.
eg:
public class MagicBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
if (bean instanceof Character) {
System.out.println("BeanPostProcessor: Adding a touch of magic to " + ((Character) bean).getName());
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof Character) {
System.out.println("BeanPostProcessor: Magic continues for " + ((Character) bean).getName());
}
return bean;
}
}
Bean Life Cycle
Spring Bean life cycle stages:
6. @PostConstruct: Customizing Bean Initialization
• The @PostConstruct annotation plays a significant role in customizing the initialization
of a bean.Execute custom logic after a bean has been initialized.
eg:
import jakarta.annotation.PostConstruct;

public class Character {

@PostConstruct
public void init() {
System.out.println("@PostConstruct: " + getName() + " is preparing for action.");
}
}
Bean Life Cycle
Spring Bean life cycle stages:
7. InitializingBean: Preparing for Action
• As the bean gets closer to being fully operational, it enters the initialization stage. This
stage provides an opportunity for executing custom setup logic after properties are set
and before the bean is ready for use.
eg:
public class Character implements InitializingBean {
@Override
public void afterPropertiesSet() {
System.out.println("Initialization: " + getName() + " is undergoing intensive
training.");
}
// Other methods
}
Bean Life Cycle
Spring Bean life cycle stages:
8. Custom Initialization: Tailored Setup
• Perform unique setup tasks for the bean.
• Execute specialized initialization logic.
eg:
public class Character {
public void customInit() {
System.out.println("Custom Initialization: Executing custom init for " + getName());
performSpecialTraining();
}
private void performSpecialTraining() {
System.out.println("Custom Initialization: " + getName() + " is performing a special
training routine.");
}
// Other methods
}
Bean Life Cycle
Spring Bean life cycle stages:
9. @PreDestroy: Preparing for Cleanup
• the @PreDestroy annotation marks a method within a bean as a pre-destruction
callback. This means that the annotated method is executed just before the bean is
removed or destroyed by the Spring container. It offers an opportunity to perform
cleanup operations and release resources gracefully before the bean’s final disposal.
eg:
import jakarta.annotation.PreDestroy;
public class Character {
@PreDestroy
public void preDestroyCleanup() {
System.out.println("@PreDestroy: " + getName() + " is saying goodbye and preparing
to rest.");
}
}}
Bean Life Cycle
Spring Bean life cycle stages:
10. DisposableBean: Bidding Farewell
• The DisposableBean interface provides a method for executing cleanup operations
before the bean is destroyed.
eg:
public class Character implements DisposableBean {
@Override
public void destroy() {
System.out.println("DisposableBean: " + getName() + " is saying goodbye and
resting.");
restAndRecover();
}
private void restAndRecover() {
System.out.println("DisposableBean: " + getName() + " is resting and recovering
energy.");
} }
Bean Life Cycle
Spring Bean life cycle stages:
11. Custom Destruction: Parting Moments
• In addition to standard destruction methods, you can implement custom destruction
logic. This allows you to perform any final actions before the bean’s departure.
eg:
public class Character {
public void customDestroy() {
System.out.println("Custom Destruction: " + getName() + " is bidding farewell and performing a final
action.");
sayGoodbye();
performFinalAction();
}
private void sayGoodbye() {
System.out.println("Custom Destruction: " + getName() + " says goodbye.");
}
private void performFinalAction() {
System.out.println("Custom Destruction: " + getName() + " performs a final action.");
} }
XML Configuration on Spring
• XML configuration is a fundamental part of the Spring
Framework.
• It allows developers to define the application context, including
beans and their dependencies, in a structured way.
1. Application Context
• The application context is the central interface to the Spring IoC
(Inversion of Control) container.
• It is responsible for instantiating, configuring, and managing the
lifecycle of beans defined in the XML configuration file.
XML Configuration on Spring
2. Beans
• A bean is an object that is instantiated, assembled, and
managed by the Spring IoC container.
• Beans are defined in the XML file using the <bean> element,
which includes several attributes:
• id: A unique identifier for the bean.
• class: The fully qualified name of the class to instantiate.
• scope: Defines the lifecycle of the bean (e.g., singleton, prototype).

• Example:
<bean id="myBean" class="com.example.MyBean" scope="singleton"/>
XML Configuration on Spring

3. Dependency Injection
• Spring supports various types of dependency injection:
• Constructor Injection: Dependencies are provided as constructor
arguments.
• Setter Injection: Dependencies are set through setter methods.
• Example Setter Code:
<bean id="myService" class="com.example.MyService">
<property name="myRepository" ref="myRepository" />
</bean>
<bean id="myRepository" class="com.example.MyRepository" />
XML Configuration on Spring
4. Namespaces and Schema Validation
• XML configuration can utilize different namespaces to support various Spring
features, such as AOP, transactions, and more.
• The xsi:schemaLocation attribute helps ensure that the XML file is validated
against the correct Spring schemas.
• Example:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-
beans.xsd">
XML Configuration on Spring
5. Profile
• Profiles allows user to define different configurations for different environments
(e.g., development, testing, production). User can specify active profiles in your
XML configuration.
• Example:
<beans profile="development">
<bean id="myService" class="com.example.DevMyService"/>
</beans>
<beans profile="production">
<bean id="myService" class="com.example.ProdMyService"/>
</beans>
Aspect-Oriented Programming
• Spring allows user to define methods that will be called during the bean
lifecycle.
• User can specify initialization and destruction methods directly in the XML
configuration.
Example:
<bean id="myBean" class="com.example.MyBean" init-method="init" destroy-
method="cleanup"/>
Aspect-Oriented Programming
• Aspect-oriented Programming (AOP) complements Object-
oriented Programming (OOP) by providing another way of
thinking about program structure.
• The key unit of modularity in OOP is the class, whereas in AOP
the unit of modularity is the aspect.
• Aspects enable the modularization of concerns (such as
transaction management) that cut across multiple types and
objects.
• (Such concerns are often termed "crosscutting" concerns in AOP literature.)
Aspect-Oriented Programming
• One of the key components of Spring is the AOP framework.
• AOP is used in the Spring Framework to:
• Provide declarative enterprise services. The most important such service
is declarative transaction management.
• Let users implement custom aspects, complementing their use of OOP
with AOP.
Aspect-Oriented Programming
AOP Concepts
Aspect:
• A modularization of a concern that cuts across multiple classes.
• Transaction management is a good example of a crosscutting
concern in enterprise Java applications.
• In Spring AOP, aspects are implemented by using regular
classes (the schema-based approach) or regular classes
annotated with the @Aspect annotation (the @AspectJ style).
Aspect-Oriented Programming
AOP Concepts
Join point:
• A point during the execution of a program, such as the execution
of a method or the handling of an exception.
• In Spring AOP, a join point always represents a method
execution.
Advice:
• Action taken by an aspect at a particular join point.
• Different types of advice include "around", "before", and "after"
advice.
• Many AOP frameworks, including Spring, model an advice as an
interceptor and maintain a chain of interceptors around the join
point.
Aspect-Oriented Programming
AOP Concepts
Target object:
• An object being advised by one or more aspects. Also referred
to as the "advised object".
• Since Spring AOP is implemented by using runtime proxies, this
object is always a proxied object.
AOP proxy:
• An object created by the AOP framework in order to implement
the aspect contracts (advice method executions and so on).
• In the Spring Framework, an AOP proxy is a JDK dynamic
proxy or a CGLIB proxy.
Aspect-Oriented Programming
AOP Concepts
Weaving:
• Linking aspects with other application types or objects to create
an advised object.
• This can be done at compile time (using the AspectJ compiler,
for example), load time, or at runtime.
• Spring AOP, like other pure Java AOP frameworks, performs
weaving at runtime.
Aspect-Oriented Programming
Spring AOP includes the following types of advice:
• Before advice: Advice that runs before a join point but that
does not have the ability to prevent execution flow proceeding
to the join point (unless it throws an exception).
• After returning advice: Advice to be run after a join point
completes normally (for example, if a method returns without
throwing an exception).
•After throwing advice: Advice to be run if a method exits by
throwing an exception.
Aspect-Oriented Programming
• After (finally) advice: Advice to be run regardless of the means
by which a join point exits (normal or exceptional return).
• Around advice: Advice that surrounds a join point such as a
method invocation. This is the most powerful kind of advice.
Around advice can perform custom behavior before and after
the method invocation. It is also responsible for choosing
whether to proceed to the join point or to shortcut the advised
method execution by returning its own return value or throwing
an exception.

You might also like