Java Web Framework - Spring
Java Web Framework - Spring
Java Web Framework - Spring
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
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
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
• 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
@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.