Spring Complete Notes

Prepared by Srikanth Mamillapalli

Structured HTML learning notes covering Spring Core, IoC/DI, Beans, AOP, JDBC, Transactions and Spring MVC.

Format: This version reconstructs the textual content from the supplied PDF into a responsive learning portal. Original PDF page images/screenshots are intentionally not included.

Spring Introduction

SPRING Introduction

  • Spring is a lightweight & open source, loosely coupled, Aspect oriented, Dependency Injection

Java application framework to develop various types of java applications.

  • Spring introduced by Rod Johnson in 2003 year.
  • Spring is a master of all frameworks of frameworks because it provides support to various

frameworks such as Struts, JSE, Prime Faces, Hibernate, Tapestry, Kafka, EJB, JMS, Rabbit…

  • Spring is a complete & a modular framework and can be used for all layer implementations for

a real time application or spring can be used layer of real time applications unlike struts,

Hibernate.

  • Spring framework is said to be a non-invasive means it doesn’t force a programmer to extend

or implement the class from any fore defined class or interface given by spring API.

  • Spring is light weight frame work because of
  • POJO/POJI Model
  • Jar file size
  • Spring container

Spring Features:

  • 1.Simplicity
  • Non invasive
  • POJI & POJI
  • Testability
  • Spring is having its own container to run the application.
  • POJO Based - Spring enables developers to develop enterprise-class applications using POJOs.

The benefit of using only POJOs is that you do not need an EJB container product such as an

application server but you have the option of using only a robust servlet container such as

Tomcat or some commercial product.

  • Modular - Spring is organized in a modular fashion. Even though the number of packages and

classes are substantial, you have to worry only about the ones you need and ignore the rest.

  • Integration with existing frameworks - Spring does not reinvent the wheel, instead it truly

makes use of some of the existing technologies like several ORM frameworks, logging

frameworks, JEE, Quartz and JDK timers, and other view technologies.

  • Web MVC - Spring's web framework is a well-designed web MVC framework, which provides a

great alternative to web frameworks such as Struts or other over-engineered or less popular

web frameworks.

  • Transaction management - Spring provides a consistent transaction management interface

that can scale down to a local transaction (using a single database, for example) and scale up

to global transactions (using JTA, for example).

Can we implement entire project with single class?

Definitely we can use multiple classes if we write multiple classes’ then one class may be depend on

the other class.

Flipkart Courier system

Amazon Shopping service

Both classes are in collaboration.

  • Spring bean is a simple java class
  • The objects that form the backbone of your application and that are managed by the Spring

IoC container are called beans. A bean is an object that is instantiated, assembled, and

otherwise managed by a Spring IoC container. These beans are created with the configuration

metadata that you supply to the container.

  • The bean classes are created and managed by spring container or spring IOC container.
  • Degree of dependency is more then those beans are called tightly coupled
  • Fan & Switch
  • Degree of dependency is less then those beans are called loosely coupled
  • TV & Remote & Mobile
  • Keeping Bean classes in dependency is called Bean collaboration.

Spring Framework Architecture

Core Container
Beans • Core • Context • SpEL
AOP / Aspects
Cross-cutting concerns
Data Access / Integration
JDBC • ORM • JMS • Transactions
Web / MVC / Remoting
Web • Servlet • WebSocket

IoC, Dependency Lookup & Dependency Injection

Different approaches of designing class having dependency

Approach 1: Composition

Making Target class having dependent class object.

Approach 2: Factory pattern

Make Target class getting dependent class from a factory.

Note: Factory is a DP that tells you asked me a object I will give a object but don’t ask me how to

create an object.

Car Factory Car

Biscuit Factory Biscuit

Approach 3: JNDI Registry

Make target class getting dependent class object from a JNDI Registry

Note: Local Variable

Instance Variable

Static Variable

More global visibility JNDI Registry if you want to provide Global visibility/accessibility to object make

sure that object placed in JNDI Registry access from Remote/Local/Java classes

Approach 4: Inheritance

Make target class extending from Dependent class.

Approach 5: IOC

Make IOC container/ Framework injecting dependent class object to target class object.

IOC

IOC or Inversion of Control is a design pattern.

If controlling the application class inverted to the third party then it is called IOC.

Spring container also we can call it as an IOC container

  • Dependency lookup/pull
  • Dependency Injection/push

Dependency lookup/pull

It is an approach where we can get the resource after demand.

Ex: Factory, Registry

Dependency Injection/push

  • The dependency injection is a Design pattern that removes the dependency of the program.
  • IOC/DI describes the situation where one object uses a second object to provide a particular

capacity.

  • In such case we provide the information from the external source as XML file.
  • It makes our code loosely coupled & easier for testing.
  • In such case we provide the information from the external source such as XML file.
  • It makes our code loosely coupled & easier for testing.

Configuring spring container

  • XML configuration.
  • Java Annotations.
  • Java source code

Spring Design and Development process

  • Create & configure Bean class
  • Create spring container.
  • Retrieve Beans from spring container

Types of dependency Injection

  • Setter Injection
  • Constructor Injection.
  • Use setter injection when number of dependency is more on you need readability.
  • Use constructor injection when object must be creating with all of its dependency.

Dependency Design Approaches

ApproachIdea from the notes
CompositionTarget class contains the dependent class object.
Factory PatternTarget obtains the dependent object from a factory.
JNDI RegistryTarget obtains the dependent object from a JNDI registry.
InheritanceTarget extends the dependent class.
IoCIoC container/framework injects the dependent object into the target.

Spring Beans & Configuration Metadata

SPRING BEAN

Bean

  • The objects that form the backbone of your application and that are managed by the Spring

IoC container are called beans.

  • A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC

container. These beans are created with the configuration metadata that you supply to the

container.

  • For example, in the form of XML <bean/> definitions which you have already seen in the

previous chapters.

  • Bean definition contains the information called configuration metadata, which is needed for

the container to know the following −

  • How to create a bean
  • Bean's lifecycle details
  • Bean's dependencies
Sr.No. Properties & Description

1 class

This attribute is mandatory and specifies the bean class to be used to create the bean.

2 name

This attribute specifies the bean identifier uniquely. In XMLbased configuration metadata, you use

the id and/or name attributes to specify the bean identifier(s).

3 scope

This attribute specifies the scope of the objects created from a p articular bean definition and it

will be discussed in bean scopes chapter.

4 constructor-arg

This is used to inject the dependencies and will be discussed in subsequent chapters.

5 properties

This is used to inject the dependencies and will be discussed in subsequent chapters.

6 autowiring mode

This is used to inject the dependencies and will be discussed in subsequent chapters.

7 lazy-initialization mode

A lazy-initialized bean tells the IoC container to create a bean instance when it is first requeste d,

rather than at the startup.

8 initialization method

A callback to be called just after all necessary properties on the bean have been set by the

container. It will be discussed in bean life cycle chapter.

9 destruction method

A callback to be used whe n the container containing the bean is destroyed. It will be discussed in

bean life cycle chapter.

Spring Configuration Metadata

  • Spring IoC container is totally decoupled from the format in which this configuration metadata

is actually written. Following are the three important methods to provide configuration

metadata to the Spring Container −

  • XML based configuration file.
  • Annotation-based configuration
  • Java-based configuration
  • You already have seen how XML-based configuration metadata is provided to the container,

but let us see another sample of XML-based configuration file with different bean definitions

including lazy initialization, initialization method, and destruction method –

  • <?xml version = "1.0" encoding = "UTF-8"?>
  • <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-

4.0.xsd">

  • <!-- A simple bean definition -->
  • <bean id = "..." class = "...">
  • <!-- collaborators and configuration for this bean go

here -->

  • </bean>
  • <!-- A bean definition with lazy init set on -->
  • <bean id = "..." class = "..." lazy-init = "true">
  • <!-- collaborators and configuration for this bean go

here -->

  • </bean>
  • <!-- A bean definition with initialization method -->
  • <bean id = "..." class = "..." init-method = "...">
  • <!-- collaborators and configuration for this bean go

here -->

  • </bean>
  • <!-- A bean definition with destruction method -->
  • <bean id = "..." class = "..." destroy-method = "...">
  • <!-- collaborators and configuration for this bean go

here -->

  • </bean>
  • <!-- more bean definitions go here -->
  • </beans>

Bean scope

Sr.No. Scope & Description

1 singleton

This scopes the bean definition to a single instance per Spring IoC container (default).

2 prototype

This scopes a single bean definition to have any number of object instances.

3 request

This scopes a bean definition to an HTTP request. Only valid in the con text of a web-aware Spring

ApplicationContext.

4 session

This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring

ApplicationContext.

5 global-session

This scopes a bean definition to a global HTTP session. Only v alid in the context of a web -aware

Spring ApplicationContext.

Singleton if the scope is set to singleton, the spring IOC container creates exactly one instance

of the object defined by that bean definition. The single instance is stored in each of such

singleton beans and all subsequent requests and references for that named bean returns the

cached object .The default scope is always singleton.

Prototype If scope is set to be Prototype ,the spring IOC container creates new bean instance

of the object. Every time a request for the specific bean is made.

Request HTTP Request

Session HTTP session

Global Session Global Session/Application Context/Servlet Context

Example

Let us have a working Eclipse IDE in place and take the following steps to create a Spring application

Bean Scopes at a Glance

ScopeDescription
singletonSingle instance per Spring IoC container; default scope.
prototypeNew instance whenever the bean is requested.
requestOne bean instance per HTTP request in a web-aware ApplicationContext.
sessionBean scoped to an HTTP session.
global-sessionBean scoped to a global HTTP session.

Bean Lifecycle & Lookup Method Injection

Steps Description

1 Create a project with a name SpringExample and create a package com.boolean under the src folder

in the created project.

2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World

Example chapter.

3 Create Java classes HelloWorld and MainApp under the com. boolean package.

4 Create Beans configuration file Beans.xml under the src folder.

5 The final step is to create the content of all the Java files and Bean Configuration file and run the

application as explained below.

BEAN LIFE CYCLE

  • Initialization callbacks
  • Destruction Callbacks
  • Default initialization
  • Default destroy method

Bean life cycle

  • When bean is instantiated it may be required to perform some initialization to get it

into a usable state.

  • When the bean is no longer required and is removed from the container some clean up

may be required.

The init-method attribute specifies a method that is to be called on the bean immediately

upon instantiation similarly destroy method specifies a method that is called just before a

bean is removed from the container.

Class implements initialize Bean { 
 Public void afterPropertySet (){ 
 } 
 }

In care of xml configuration

<bean id= “simplebean “ class =”com.intucal.ums.adobe.samplebean”

Init-method =”init”/>

Destruction call Backs

Org.springframework.bean factory .disposable Bean interface specifies a single

method.

Public class sampleBean implements Disposable Band { 
 Public void destroy(){ 
 } 
 }

Xml configuration:

< bean id =”xyz” class =” destroy method “= “ destroy method”/>

Register shutdown Hook

This method that is declared on the abstract application context class

This will ensures a graceful shutdown &calls the relevant destroy () method.

Application context context= new ClassPathXmlApplicationContext(“bean-xml”); 
context.registerShutdownHook ();

Default initialization& destroy method :->

If you have to many beans having initializing and destroy with the same name you

don’t need to be declare intit-method and destroy method on each individual bean.

Instead frame work provides the flexibility to configure such situation using default init-

method & destroy –methods. Attribute on the <bean> element in the xml file.

beans xml:

Default –init-method =”init”

Default- destroy –method “destroy”

</bean>

Lookup method injection

Lookup method injection refers to the ability of the container to override methods on

container managed beans, to return the result of looking up another named bean in the

container.

The lookup will typically be of a prototype bean.

<bean id =”xyz” class=” com.sree.sample”>

<lookup-method =”get current time “bean =”current time bean “/>

<bean/> 
<bean id =” current time bean “ class=” java.sql.timestamp” Scope=” prototype”/>

BeanFactory, ApplicationContext & BeanPostProcessor

Spring Bean Factory Container

This is the simplest container providing basic support for D1 and defined by the org.spring

framework. Beans, factory Bean Factory interface. The Bean Factory and related interface

such as Bean Factory Aware, Initialize Bean, and disposable Beans are still present in the

spring for the purpose of backward compellability with the large number of third party

frameworks that integrate with the spring.

Spring Application Context Container

This container adds more enterprise specific functionality such as the ability to resolve textual

message from a properties file and the ability to publish application events to interested event

lustiness .application context container includes all the functionally of the Bean Factory

container, so it is generally recommended over the Bean Factory.

Bean Factory can still be used for light weight applications like mobile devices and applet

based applications where data volume and speed in significant

  • Application context allows more than one config files to exist while Bean Factory

permits one.

  • Application context can print events to Beans registered as listless. This feature is not

supported by Bean Factory.

  • Application context also provides support for applications of lifecycle events,

internationalization messages and validation and also provides services like EJB

integration, remoting, JNDI access and scheduling. These features are not supported by

Bean Factory.

Auto wiring is used to build relationships between the collaborating Beans. Spring container

can automatically resolve collaborator for Beans. It means to look for objects define In Spring

with the same name as your object property.

BEAN POSTPROCESSORS

This interface defines call back methods that you can implement to provide your own

instantiation logic, dependency resolution logic etc.

  • Post process before initialization
  • Post process after initialization
public class XYZ implements Bean Post Processor { 
 Object post process beforeInitialization (Object Bean, String BeanName) {

Return bean;

} 
public object Post Process afterInitialization(Object Bean, String BeanName) {

Return bean;

} 
 }

Bean Inheritance, Templates, Inner Beans & Collections

Bean Inheritance

When you use XML-based configuration meta data, you include a child bean definition

by using parent attribute, specifying bean as the value of this attribute.

<bean id =”abc” class=”Hello World” parent=”hello SAI”/> 
<bean id=”hello SAI” class=”Hello sai” > 
 <property name=”messages” value=”Hello SAI”/> 
</bean>

Bean Template

  • A bean definition in configuration metadata can contain constructor arguments,

property values etc.

  • Spring framework provides the facility to define a bean definition template which can

be used by child bean definitions.

  • To define a template remove class attribute and use abstract attribute to true in bean

definition.

Inner beans

Java inner classes are defined within the scope of other classes similarly, inner beans are

beans that are defined within the scope of another bean. Thus, a <bean/> element inside the

<property/> or <constructor-arg/> elements is called inner bean and it is shown below.
  • List This helps in wiring ie injecting a list of values, allowing duplicates.
  • Set This helps in wiring a set of values but without any duplicates.
  • Map This can be used to inject a collection of name-value pairs where name and value

can be of any type.

  • Props This can be used to inject a collection of name-value pairs where the name and

value are both Strings.

SPRING AOP

  • AOP is a programming technique that allows programmers to modularize cross

cutting concerns ,or behaviour that cuts access the typical divisions of

responsibility, such as logging and forms action management.

  • The core construct of AOP is the aspect, which encapsulates behaviour’s affecting

multiple classes into reusable modules.

  • Aspect is part of concern we are trying to implement.
  • A module which has a set of AOP’s providing cross-cutting requirements.
  • An application can have any number of aspects depending on the requirement.
  • The key unit of modularity in OOP is the class, whereas in AOP the unit of

modularity is the aspect

  • Dependency Injection helps you decouple your application objects from each other

and AOP helps you decouple cross-cutting concerns from the objects that they

affect.

  • AOP is like triggers in programming languages such as Perl, .NET, Java, and others.

AOP Terminologies

Before we start working with AOP, let us become familiar with the AOP concepts and

terminology. These terms are not specific to Spring, rather they are related to AOP.

Sr.No Terms & Description

1 Aspect

This is a module which has a set of APIs providing cross -cutting requirements. For

example, a logging module would be called AOP aspect for logging. An application can

have any number of aspects depending on the requirement.

2 Join point

This represents a point in your application where you can plug -in the AOP aspect. You can

also say, it is the actual place in the application where an action will be taken using Spring

AOP framework.

3 Advice

This is the actual action to be taken either before or after the method execution. This is an

actual piece of code that is invoked during the program execution by Spring AOP

framework.

Spring AOP

  • List This helps in wiring ie injecting a list of values, allowing duplicates.
  • Set This helps in wiring a set of values but without any duplicates.
  • Map This can be used to inject a collection of name-value pairs where name and value

can be of any type.

  • Props This can be used to inject a collection of name-value pairs where the name and

value are both Strings.

SPRING AOP

  • AOP is a programming technique that allows programmers to modularize cross

cutting concerns ,or behaviour that cuts access the typical divisions of

responsibility, such as logging and forms action management.

  • The core construct of AOP is the aspect, which encapsulates behaviour’s affecting

multiple classes into reusable modules.

  • Aspect is part of concern we are trying to implement.
  • A module which has a set of AOP’s providing cross-cutting requirements.
  • An application can have any number of aspects depending on the requirement.
  • The key unit of modularity in OOP is the class, whereas in AOP the unit of

modularity is the aspect

  • Dependency Injection helps you decouple your application objects from each other

and AOP helps you decouple cross-cutting concerns from the objects that they

affect.

  • AOP is like triggers in programming languages such as Perl, .NET, Java, and others.

AOP Terminologies

Before we start working with AOP, let us become familiar with the AOP concepts and

terminology. These terms are not specific to Spring, rather they are related to AOP.

Sr.No Terms & Description

1 Aspect

This is a module which has a set of APIs providing cross -cutting requirements. For

example, a logging module would be called AOP aspect for logging. An application can

have any number of aspects depending on the requirement.

2 Join point

This represents a point in your application where you can plug -in the AOP aspect. You can

also say, it is the actual place in the application where an action will be taken using Spring

AOP framework.

3 Advice

This is the actual action to be taken either before or after the method execution. This is an

actual piece of code that is invoked during the program execution by Spring AOP

framework.

4 Pointcut

This is a set o f one or more join points where an advice should be executed. You can

specify pointcuts using expressions or patterns as we will see in our AOP examples.

5 Introduction

An introduction allows you to add new methods or attributes to the existing classes.

6 Target object

The object being advised by one or more aspects. This object will always be a proxied

object, also referred to as the advised object.

7 Weaving

Weaving is the process of linking aspects with other application types or objects to create

an advised object. This can be done at compile time, load time, or at runtime.

Types of Advice

Spring aspects can work with five kinds of advice mentioned as follows −

Sr.No Advice & Description

1 before

Run advice before the a method execution.

2 after

Run advice after the method execution, regardless of its outcome.

3 after-returning

Run advice after the a method execution only if method completes successfully.

4 after-throwing

Run advice after the a method execution only if method exits by throwing an exception.

5 around

Run advice before and after the advised method is invoked.

Custom Aspects Implementation

Spring supports the @AspectJ annotation style approach and the schema-based approach to

implement custom aspects. These two approaches have been explained in detail in the

following sections.

Sr.No Approach & Description

1 XML Schema based

Aspects are implemented using the regular classes along with XML based configuration.

2 @AspectJ based

@AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java

5 annotations.

@Aspect 
 Public class logging aspect { 
 @Before (“execution(*com. intucal/.service.*.get*())”) 
 Public void get all advice() {

s.o.p (“service method”):

} 
}

AOP Advice Types

AdviceWhen it runs
beforeBefore method execution.
afterAfter method execution, regardless of outcome.
after-returningAfter successful method completion.
after-throwingAfter the method exits by throwing an exception.
aroundBefore and after the advised method is invoked.

Spring JDBC & JdbcTemplate

Spring - JDBC Framework Overview

  • While working with the database using plain old JDBC, it becomes cumbersome to

write unnecessary code to handle exceptions, opening and closing database

connections, etc.

  • However, Spring JDBC Framework takes care o f all the low -level details starting from

opening the connection, prepare and execute the SQL statement, process exceptions,

handle transactions and finally close the connection.

  • So what you have to do is just define the connection parameters and specify t he SQL

statement to be executed and do the required work for each iteration while fetching

data from the database.

  • Spring JDBC provides several approaches and correspondingly different classes to

interface with the database. I'm going to take classic and t he most popular approach

which makes use of JdbcTemplate class of the framework.

  • This is the central framework class that manages all the database communication and

exception handling.

JdbcTemplate Class

  • The JDBC Template class executes SQL queries, upda tes statements, stores procedure

calls, performs iteration over ResultSets, and extracts returned parameter values.

  • It also catches JDBC exceptions and translates them to the generic, more informative,

exception hierarchy defined in the org.springframework.dao package.

  • Instances of the JdbcTemplate class are threadsafe once configured. So you can

configure a single instance of a JdbcTemplate and then safely inject this shared

reference into multiple DAOs.

  • A common practice when using the JDBC Template class is to configure

a DataSource in your Spring configuration file, and then dependency -inject that

shared DataSource bean into your DAO classes, and the JdbcTemplate is created in

the setter for the DataSource.

Configuring Data Source

Data Access Object (DAO)

  • DAO stands for Data Access Object, which is commonly used for database interaction.

DAOs exist to provide a means to read and write data to the database and they

should expose this functionality through an interface by which the rest of the

application will access them.

  • The DAO support in Spring makes it easy to work with data access technologies like

JDBC, Hibernate, JPA, or JDO in a consistent way.

Executing SQL statements

Let us see how we can perform CRUD (Create, Read, Update and Delete) operat ion on

database tables using SQL and JDBC Template object.

Querying for an integer

String SQL = "select count(*) from Student"; 
int rowCount = jdbcTemplateObject.queryForInt( SQL );

Querying for a long

String SQL = "select count(*) from Student"; 
long rowCount = jdbcTemplateObject.queryForLong( SQL );

A simple query using a bind variable

String SQL = "select age from Student where id = ?"; 
int age = jdbcTemplateObject.queryForInt(SQL, new Object[]{10});

Querying for a String

String SQL = "select name from Student where id = ?"; 
String name = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, String.class);

Querying and returning an object

String SQL = "select * from Student where id = ?"; 
Student student = jdbcTemplateObject.queryForObject( 
 SQL, new Object[]{10}, new StudentMapper()); 

public class StudentMapper implements RowMapper<Student> { 
 public Student mapRow(ResultSet rs, int rowNum) throws SQLException { 
 Student student = new Student(); 
 student.setID(rs.getInt("id")); 
 student.setName(rs.getString("name")); 
 student.setAge(rs.getInt("age"));

return student;

} 
}

Querying and returning multiple objects

String SQL = "select * from Student"; 
List<Student> students = jdbcTemplateObject.query( 
 SQL, new StudentMapper()); 

public class StudentMapper implements RowMapper<Student> { 
 public Student mapRow(ResultSet rs, int rowNum) throws SQLException { 
 Student student = new Student(); 
 student.setID(rs.getInt("id")); 
 student.setName(rs.getString("name")); 
 student.setAge(rs.getInt("age"));

return student;

} 
}

Inserting a row into the table

String SQL = "insert into Student (name, age) values (?, ?)"; 
jdbcTemplateObject.update( SQL, new Object[]{"Sree", 11} );

Updating a row into the table

String SQL = "update Student set name = ? where id = ?"; 
jdbcTemplateObject.update( SQL, new Object[]{"Sree", 10} );

Deleting a row from the table

String SQL = "delete Student where id = ?"; 
jdbcTemplateObject.update( SQL, new Object[]{20} );

SQL Stored Procedure in Spring

public Student getStudent(Integer id) {

SqlParameterSource in = new

MapSqlParameterSource().addValue("in_id", id); 
 Map<String, Object> out = jdbcCall.execute(in); 

 Student student = new Student(); 
 student.setId(id); 
 student.setName((String) out.get("out_name")); 
 student.setAge((Integer) out.get("out_age"));

return student;

}

Spring - Transaction Management

A database transaction is a sequence of actions that are treated as a single unit of work. These actions

should either complete entirely or take no effect at all. Transaction management is an important part

of RDBMS -oriented enterprise application to ensure data integrity and consistency. The concept of

transactions can be described with the following four key properties described as ACID −

  • Atomicity − A transaction should be treated as a single unit of operation, which means either

the entire sequence of operations is successful or unsuccessful.

  • Consistency − This represents the consistency of the referential integrity of the database,

unique primary keys in tables, etc.

  • Isolation − There may be many transaction processing with the same data set at the same

time. Each transaction should be isolated from others to prevent data corruption.

  • Durability − Once a transaction has completed, the results of this transaction have to be made

permanent and cannot be erased from the database due to system failure.

A real RDBMS database system will guarantee all four properties for each transaction. The simplistic

view of a transaction issued to the database using SQL is as follows −

  • Begin the transaction using begin transaction command.
  • Perform various deleted, update or insert operations using SQL queries.
  • If all the operation are successful then perform commit otherwise rollback all the operations.

Spring framework provides an abstract layer on top of different underlying transaction management

APIs. Spring's transaction support aims to provide an alternative to EJB transactions by adding

Spring Transaction Management

} 
}

Inserting a row into the table

String SQL = "insert into Student (name, age) values (?, ?)"; 
jdbcTemplateObject.update( SQL, new Object[]{"Sree", 11} );

Updating a row into the table

String SQL = "update Student set name = ? where id = ?"; 
jdbcTemplateObject.update( SQL, new Object[]{"Sree", 10} );

Deleting a row from the table

String SQL = "delete Student where id = ?"; 
jdbcTemplateObject.update( SQL, new Object[]{20} );

SQL Stored Procedure in Spring

public Student getStudent(Integer id) {

SqlParameterSource in = new

MapSqlParameterSource().addValue("in_id", id); 
 Map<String, Object> out = jdbcCall.execute(in); 

 Student student = new Student(); 
 student.setId(id); 
 student.setName((String) out.get("out_name")); 
 student.setAge((Integer) out.get("out_age"));

return student;

}

Spring - Transaction Management

A database transaction is a sequence of actions that are treated as a single unit of work. These actions

should either complete entirely or take no effect at all. Transaction management is an important part

of RDBMS -oriented enterprise application to ensure data integrity and consistency. The concept of

transactions can be described with the following four key properties described as ACID −

  • Atomicity − A transaction should be treated as a single unit of operation, which means either

the entire sequence of operations is successful or unsuccessful.

  • Consistency − This represents the consistency of the referential integrity of the database,

unique primary keys in tables, etc.

  • Isolation − There may be many transaction processing with the same data set at the same

time. Each transaction should be isolated from others to prevent data corruption.

  • Durability − Once a transaction has completed, the results of this transaction have to be made

permanent and cannot be erased from the database due to system failure.

A real RDBMS database system will guarantee all four properties for each transaction. The simplistic

view of a transaction issued to the database using SQL is as follows −

  • Begin the transaction using begin transaction command.
  • Perform various deleted, update or insert operations using SQL queries.
  • If all the operation are successful then perform commit otherwise rollback all the operations.

Spring framework provides an abstract layer on top of different underlying transaction management

APIs. Spring's transaction support aims to provide an alternative to EJB transactions by adding

transaction capabilities to POJOs. Spring supports both programma tic and declarative transaction

management. EJBs require an application server, but Spring transaction management can be

implemented without the need of an application server.

Local vs. Global Transactions

Local transactions are specific to a single transa ctional resource like a JDBC connection, whereas

global transactions can span multiple transactional resources like transaction in a distributed system.

Local transaction management can be useful in a centralized computing environment where

application components and resources are located at a single site, and transaction management only

involves a local data manager running on a single machine. Local transactions are easier to be

implemented.

Global transaction management is required in a distributed compu ting environment where all the

resources are distributed across multiple systems. In such a case, transaction management needs to

be done both at local and global levels. A distributed or a global transaction is executed across

multiple systems, and its ex ecution requires coordination between the global transaction

management system and all the local data managers of all the involved systems.

Programmatic vs. Declarative

Spring supports two types of transaction management −

  • Programmatic transaction management − This means that you have to manage the

transaction with the help of programming. T hat gives you extreme flexibility, but it is difficult

to maintain.

  • Declarative transaction management − This means you separate transaction management

from the business code. You only use annotations or XML -based configuration to manage the

transactions.

Declarative transaction management is preferable over programmatic transaction management

though it is less flexible than programmatic transaction management, which allows you to control

transactions through your code. But as a kind of crosscutting concern, declarative transaction

management can be modularized with the AOP approach. Spring supports declarative transaction

management through the Spring AOP framework.

Spring Transaction Abstractions

The key to the Spring transaction abstraction is defined by

the org.springframework.transaction.PlatformTransactionManager interface, which is as follows −

public interface PlatformTransactionManager { 
 TransactionStatus getTransaction(TransactionDefinition definition);

throws TransactionException;

void commit(TransactionStatus status) throws TransactionException;

void rollback(TransactionStatus status) throws TransactionException;

}
Sr.No Method & Description

1 TransactionStatus getTransaction(TransactionDefinition definition)

This method returns a currently active transaction or creates a new one, according t o the specified

propagation behavior.

2 void commit(TransactionStatus status)

This method commits the given transaction, with regard to its status.

3 void rollback(TransactionStatus status)

This method performs a rollback of the given transaction.

The TransactionDefinition is the core interface of the transaction support in Spring and it is defined as

follows −

public interface TransactionDefinition { 
 int getPropagationBehavior(); 
 int getIsolationLevel(); 
 String getName(); 
 int getTimeout(); 
 boolean isReadOnly(); 
}
Sr.No Method & Description

1 int getPropagationBehavior()

This method returns the propagation behavior. Spring offers all of the transaction propagation

options familiar from EJB CMT.

2 int getIsolationLevel()

This method return s the degree to which this transaction is isolated from the work of other

transactions.

3 String getName()

This method returns the name of this transaction.

4 int getTimeout()

This method returns the time in seconds in which the transaction must complete.

5 boolean isReadOnly()

This method returns whether the transaction is read-only.

Following are the possible values for isolation level −

Sr.No Isolation & Description

1 TransactionDefinition.ISOLATION_DEFAULT

This is the default isolation level.

2 TransactionDefinition.ISOLATION_READ_COMMITTED

Indicates that dirty reads are prevented; non-repeatable reads and phantom reads can occur.

3 TransactionDefinition.ISOLATION_READ_UNCOMMITTED

Indicates that dirty reads, non-repeatable reads, and phantom reads can occur.

4 TransactionDefinition.ISOLATION_REPEATABLE_READ

Indicates that dirty reads and non-repeatable reads are prevented; phantom reads can occur.

5 TransactionDefinition.ISOLATION_SERIALIZABLE

Indicates that dirty reads, non-repeatable reads, and phantom reads are prevented.

Following are the possible values for propagation types −

Sr.No. Propagation & Description

1 TransactionDefinition.PROPAGATION_MANDATORY

Supports a current transaction; throws an exception if no current transaction exists.

2 TransactionDefinition.PROPAGATION_NESTED

Executes within a nested transaction if a current transaction exists.

3 TransactionDefinition.PROPAGATION_NEVER

Does not support a current transaction; throws an exception if a current transaction exists.

4 TransactionDefinition.PROPAGATION_NOT_SUPPORTED

Does not support a current transaction; rather always execute nontransactionally.

5 TransactionDefinition.PROPAGATION_REQUIRED

Supports a current transaction; creates a new one if none exists.

6 TransactionDefinition.PROPAGATION_REQUIRES_NEW

Creates a new transaction, suspending the current transaction if one exists.

7 TransactionDefinition.PROPAGATION_SUPPORTS

Supports a current transaction; executes non-transactionally if none exists.

8 TransactionDefinition.TIMEOUT_DEFAULT

Uses the default timeout of the underlying transaction system, or none if timeouts are not

supported.

The TransactionStatus interface provides a simple way for transactional code to control transaction

execution and query transaction status.

public interface TransactionStatus extends SavepointManager { 
 boolean isNewTransaction(); 
 boolean hasSavepoint(); 
 void setRollbackOnly(); 
 boolean isRollbackOnly(); 
 boolean isCompleted(); 
}
Sr.No. Method & Description

1 boolean hasSavepoint()

This method returns whether this transaction internally carries a savepoint, i.e., has been created

as nested transaction based on a savepoint.

2 boolean isCompleted()

This method returns whether this transaction is completed, i.e., whether it has a lready been

committed or rolled back.

3 boolean isNewTransaction()

This method returns true in case the present transaction is new.

4 boolean isRollbackOnly()

This method returns whether the transaction has been marked as rollback-only.

5 void setRollbackOnly()

This method sets the transaction as rollback-only.

Spring - MVC Framework

  • MVC is a design pattern which provides a solution to layer an application by
  • separating Business(Model), Presentation(View) and Control Flow(Controller).

Transaction Isolation Levels

IsolationSource description
ISOLATION_DEFAULTDefault isolation level.
ISOLATION_READ_COMMITTEDDirty reads are prevented; non-repeatable and phantom reads can occur.
ISOLATION_READ_UNCOMMITTEDDirty, non-repeatable, and phantom reads can occur.
ISOLATION_REPEATABLE_READDirty and non-repeatable reads are prevented; phantom reads can occur.
ISOLATION_SERIALIZABLEDirty, non-repeatable, and phantom reads are prevented.

Transaction Propagation

PropagationSource description
MANDATORYSupports a current transaction; exception if none exists.
NESTEDNested transaction if a current transaction exists.
NEVERDoes not support a current transaction; exception if one exists.
NOT_SUPPORTEDAlways executes non-transactionally.
REQUIREDUses current transaction or creates one if none exists.
REQUIRES_NEWCreates a new transaction and suspends the current one.
SUPPORTSUses current transaction; otherwise executes non-transactionally.

Spring MVC & DispatcherServlet

8 TransactionDefinition.TIMEOUT_DEFAULT

Uses the default timeout of the underlying transaction system, or none if timeouts are not

supported.

The TransactionStatus interface provides a simple way for transactional code to control transaction

execution and query transaction status.

public interface TransactionStatus extends SavepointManager { 
 boolean isNewTransaction(); 
 boolean hasSavepoint(); 
 void setRollbackOnly(); 
 boolean isRollbackOnly(); 
 boolean isCompleted(); 
}
Sr.No. Method & Description

1 boolean hasSavepoint()

This method returns whether this transaction internally carries a savepoint, i.e., has been created

as nested transaction based on a savepoint.

2 boolean isCompleted()

This method returns whether this transaction is completed, i.e., whether it has a lready been

committed or rolled back.

3 boolean isNewTransaction()

This method returns true in case the present transaction is new.

4 boolean isRollbackOnly()

This method returns whether the transaction has been marked as rollback-only.

5 void setRollbackOnly()

This method sets the transaction as rollback-only.

Spring - MVC Framework

  • MVC is a design pattern which provides a solution to layer an application by
  • separating Business(Model), Presentation(View) and Control Flow(Controller).
  • The Spring Web MVC framework provides Model-View-Controller (MVC) architecture and

ready components that can be used to develop flexible and loosely coupled web

applications.

  • The MVC pattern results in separating the different aspects of the application (input logic,

business logic, and UI logic), while providing a loose coupling between these elements.

  • The Spring Web MVC framework provides Model -View-Controller (MVC) architecture and

ready components that can be used to develop flexible and loosely coupled web applications.

  • The MVC pattern results in separating the different aspects of the application (input logic,

business logic, and UI logic), while providing a loose coupling between these elements.

  • The Model encapsulates the application data and in general th ey will consist of

POJO.

  • The View is responsible for rendering the model data and in general it generates

HTML output that the client's browser can interpret.

  • The Controller is responsible for processing user requests and building an

appropriate model and passes it to the view for rendering.

The DispatcherServlet

The Spring Web model -view-controller (MVC) framework is designed around a DispatcherServlet that

handles all the HTTP requests and responses. The request processing workflow of the Spring Web

MVC DispatcherServlet is illustrated in the following diagram −

Following is the sequence of events corresponding to an incoming HTTP request

to DispatcherServlet −

  • After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the

appropriate Controller.

  • The Controller takes the request and calls the appropriate service methods based on used

GET or POST method. The service method will set model data based on defined business logic

and returns view name to the DispatcherServlet.

  • The DispatcherServlet will take help from ViewResolver to pickup the defined view for the

request.

  • Once view is finalized, The DispatcherServlet passes the model data to the view which is

finally rendered on the browser.

Spring MVC Flow Diagram

  • Based on the Servlet Mappings which we provide in our web.xml, the request will be routed

by the Servlet Container to our DispatcherServlet

  • Once the request is received, the DispatcherServlet will take the help

of HandlerMapping which has been added in the Spring Configuration file and get to know

the Controller class to be called for the request received.

  • Now the request will get transferred to the Controller, the Controller then executes the

appropriate methods and returns the corresponding ModelAndView object to the

DispatcherServlet.

  • The DispatcherServlet will send the Model received to the ViewResolver to get the view

page.

  • Finally, the DispatcherServlet will pass the Model to the View page and the page will be

rendered to the user

Spring MVC Handler Mapping

HandlerMapping is an Interface to be implemented by objects that define a mapping between

requests and handler objects. By

default DispatcherServlet uses BeanNameUrlHandlerMapping and

Spring MVC Request Flow

Client / Browser
DispatcherServlet
HandlerMapping
Controller
Service / Business Logic
Model + View
ViewResolver / View

The notes describe DispatcherServlet as the central component handling HTTP requests and responses and coordinating HandlerMapping, Controller and ViewResolver.

Spring MVC Handler Mappings

  • Once view is finalized, The DispatcherServlet passes the model data to the view which is

finally rendered on the browser.

Spring MVC Flow Diagram

  • Based on the Servlet Mappings which we provide in our web.xml, the request will be routed

by the Servlet Container to our DispatcherServlet

  • Once the request is received, the DispatcherServlet will take the help

of HandlerMapping which has been added in the Spring Configuration file and get to know

the Controller class to be called for the request received.

  • Now the request will get transferred to the Controller, the Controller then executes the

appropriate methods and returns the corresponding ModelAndView object to the

DispatcherServlet.

  • The DispatcherServlet will send the Model received to the ViewResolver to get the view

page.

  • Finally, the DispatcherServlet will pass the Model to the View page and the page will be

rendered to the user

Spring MVC Handler Mapping

HandlerMapping is an Interface to be implemented by objects that define a mapping between

requests and handler objects. By

default DispatcherServlet uses BeanNameUrlHandlerMapping and

DefaultAnnot ationHandlerMapping.

In Spring we majorly use the below handler mappings

  • BeanNameUrlHandlerMapping
  • ControllerClassNameHandlerMapping
  • SimpleUrlHandlerMapping

BeanNameUrlHandlerMapping Here we will be mapping each request to a Bean directly

like below

<bean

class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

<bean name="/helloWorld.htm" class="com.boolean.HelloWorldController"

/>

<bean name="/hello*.htm" class="com.boolean.HelloWorldController" />

Using ControllerClassNameHandlerMapping

<bean

class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandl

erMapping" />

<bean class="com.boolean.HelloWorldController"></bean> 
<bean class="com.boolean.WelcomeController"></bean>

SimpleUrlHandlerMapping, this type of HandlerMapping is the simplest of

all handler mappings which allows you specify URL pattern and handler

explicitly

There are two ways of defining SimpleUrlHandlerMapping, using <value> tag

and <props> tag. SimpleUrlHandlerMapping has a property called mappings

we will be passing the URL pattern to it.

Using <value> tag

Left Side of “=” is URL Pattern and right side is the id or name of the bean

<bean

class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="mappings"> 
<value>

/welcome.htm=welcomeController

/welcome*=welcomeController

/hell*=helloWorldController

/helloWorld.htm=helloWorldController

</value>

</property>

</bean>

Using <props> tag

The property key is the URL Pattern and property value is the id or name of the

bean

<bean

class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="mappings"> 
<props> 
<prop key="/welcome.htm">welcomeController</prop> 
<prop key="/welcome*">welcomeController</prop> 
<prop key="/helloworld">helloWorldController</prop> 
<prop key="/hello*">helloWorldController</prop> 
<prop key="/HELLOworld">helloWorldController</prop>

</props>

</property>

</bean>

Folder Structure

  • Create a Dynamic Web Project “SpringMVCHandlerMappingTutorial” and

create a package for our src files “com.javainterviewpoint“

  • Place the Spring 3 jar files under WEB-INF/Lib

commons-logging-

1.1.1.jar log4j-

1.2.16.jar

slf4j-api-

1.7.5.jar slf4j-

log4j12-

1.7.5.jar

spring-aspects-

3.2.4.RELEASE.jar spring-beans-

3.2.4.RELEASE.jar spring-

context-3.2.4.RELEASE.jar

spring-core-3.2.4.RELEASE.jar

spring-expression-

3.2.4.RELEASE.jar spring-web-

3.2.4.RELEASE.jar

spring-webmvc-3.2.4.RELEASE.jar

  • Create the Java classes HelloWorldController.java and

WelcomeController.java under com.javaint erviewpoint folder.

  • Place the SpringConfig-servlet.xml and web.xml under the WEB-INF

directory

  • View files helloWorld.jsp and welcome.jsp are put under the

sub directory under WEB-INF/Jsp

Spring MVC Project / Folder Structure

<bean

class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="mappings"> 
<props> 
<prop key="/welcome.htm">welcomeController</prop> 
<prop key="/welcome*">welcomeController</prop> 
<prop key="/helloworld">helloWorldController</prop> 
<prop key="/hello*">helloWorldController</prop> 
<prop key="/HELLOworld">helloWorldController</prop>

</props>

</property>

</bean>

Folder Structure

  • Create a Dynamic Web Project “SpringMVCHandlerMappingTutorial” and

create a package for our src files “com.javainterviewpoint“

  • Place the Spring 3 jar files under WEB-INF/Lib

commons-logging-

1.1.1.jar log4j-

1.2.16.jar

slf4j-api-

1.7.5.jar slf4j-

log4j12-

1.7.5.jar

spring-aspects-

3.2.4.RELEASE.jar spring-beans-

3.2.4.RELEASE.jar spring-

context-3.2.4.RELEASE.jar

spring-core-3.2.4.RELEASE.jar

spring-expression-

3.2.4.RELEASE.jar spring-web-

3.2.4.RELEASE.jar

spring-webmvc-3.2.4.RELEASE.jar

  • Create the Java classes HelloWorldController.java and

WelcomeController.java under com.javaint erviewpoint folder.

  • Place the SpringConfig-servlet.xml and web.xml under the WEB-INF

directory

  • View files helloWorld.jsp and welcome.jsp are put under the

sub directory under WEB-INF/Jsp