Slide 1 of 49© People Strategists www.peoplestrategists.com
Spring Framework -I
Slide 2 of 49© People Strategists www.peoplestrategists.com
Objectives
In this session, you will learn to:
Introduce the Spring framework
Explore the Spring architecture
Explore Spring core container and beans
Manage application object
Introduce bean factory
Introduce application context
Identify XML based configuration
Identify annotation driven configuration
Slide 3 of 49© People Strategists www.peoplestrategists.com
Spring Framework:
Is a popular non-standard open-source framework developed by
Interface21 Inc.
Aims to overcome the application problems by enabling the use of
simple JavaBeans (POJOs) to implement the business logic.
Enables the developers to create and test applications easily.
Aims to minimize the dependency of application code on its
framework.
Enables the use of simplicity and ease of testability in standalone
applications.
Introducing Spring Framework
Slide 4 of 49© People Strategists www.peoplestrategists.com
Introducing Spring Framework (Contd.)
Features of
PluggabilityDependency Injection (DI)
Aspect-Oriented
Programming (AOP)
ContainerLightweight
Slide 5 of 49© People Strategists www.peoplestrategists.com
Introducing Spring Framework (Contd.)
Pluggability:
It allows you to associate and remove business layer objects with each other
with the help of configuration files.
Spring requires you to make changes in the XML configuration file and run the
application again to take effect.
Dependency Injection (DI):
It allows you to loose coupling by creating the business layer objects based on
the description in spring configuration file.
As a result, it eases the maintenance and the testing of an application.
Aspect-Oriented Programming (AOP):
Aspect is defined as modularization of the system-wide concerns, such as
transaction management and security.
These system-level concerns are called cross-cutting concerns as they cut
across a wide range of objects within the application.
Slide 6 of 49© People Strategists www.peoplestrategists.com
Introducing Spring Framework (Contd.)
AOP is used to modularize and separate these concerns in the form of
aspects.
Container:
The Spring framework is a container that holds all the application
objects.
It is responsible for managing the life cycle and configuration of all the
application objects.
The container creates objects, which are defined in configuration files,
and associate them together.
Lightweight:
Spring is a lightweight framework that makes it easy to configure and
create complex applications.
It consists of several well-defined modules, built upon the concept of DI
and AOP.
Slide 7 of 49© People Strategists www.peoplestrategists.com
Exploring the Spring Architecture
The Spring framework has a layered architecture made up of the following seven well-defined modules, as shown in the following figure.
The Layered Architecture of the Spring Framework
Core
ORM Web Context
MVC
Application Context
DAO
AOP
Slide 8 of 49© People Strategists www.peoplestrategists.com
Exploring the Spring Architecture (Contd.)
Core
Provides the fundamental functionality of the Spring
framework.
Contains the most important component of the Spring
framework, the bean factory container.
Applies DI to separate the object initialization, creation,
and access from the actual application code.
Requires you to use the org.springframework.core
package within your Web application.
Slide 9 of 49© People Strategists www.peoplestrategists.com
Exploring the Spring Architecture (Contd.)
Aims to standardize data access work through technologies, such as
Hibernate, JDO, or JDBC.
Enables you to write simple database code without
worrying about database related tasks.
Provides an exception hierarchy for managing
database connections and handling exceptions.
Requires you to use the org.springframework.dao
package within your Web application.
DAO
Slide 10 of 49© People Strategists www.peoplestrategists.com
Exploring the Spring Architecture (Contd.)
Enables developers to integrate the Spring
framework with several other ORM tools.
Is built upon the DAO module to provide an easy way to
build DAOs for the ORM tool.
Is supported by the declarative transaction management
services of the Spring framework.
Requires you to use the org.springframework.orm
package within your Web application.
ORM
Slide 11 of 49© People Strategists www.peoplestrategists.com
Exploring the Spring Architecture (Contd.)
Enables Spring to provide support for implementing aspects within your Web
application.
Supports loose coupling of the application objects.
Enables you to separate the application logic from the
system-level services called cross-cutting concerns.
Requires you to use the org.springframework.aop
package within your Web application.
AOP
Slide 12 of 49© People Strategists www.peoplestrategists.com
Exploring the Spring Architecture (Contd.)
Provides a flexible Model-View-Controller
implementation for creating Web applications.
Enables you to separate the model and application logic
from the view or the application UI.
Enables you to integrate several other MVC
frameworks, such as Struts, and WebWorks.
Requires you to use the org.springframework.web
package within your Web application.
MVC
Slide 13 of 49© People Strategists www.peoplestrategists.com
Exploring the Spring Architecture (Contd.)
Is built on top of the core module and provides you with the ability to obtain
application resources.
Provides support for internationalization of
messages, application lifecycle events, and validations.
Provides various enterprise level services, such as JNDI
access, EJB integration, email, remoting, and scheduling.
Requires you to use the org.springframework.cont
ext package within your Web application.
Application Context
Slide 14 of 49© People Strategists www.peoplestrategists.com
Exploring the Spring Architecture (Contd.)
Is a part of its Web application development
stack, which also includes the MVC module.
Is built on top of the application context module and provides the context for
creating Web-based applications.
Supports integration of the Spring framework with various
frameworks, such as Struts, WebWorks, and JSF.
Requires you to use the org.springframework.web
package within your Web application.
Web Context
Slide 15 of 49© People Strategists www.peoplestrategists.com
The Spring framework provides the following types of containers:
Bean factory:
Is a simple container that provides support for DI.
Is defined by the org.springframework.beans.factory.BeanFactory
interface.
Application context:
Is built upon the concept of the bean factory container and provides other
functionalities, such as easy integration with Spring AOP features and support
for internationalization.
Is defined by the org.springframework.cotext.ApplicationContext
interface.
Managing Application Object
Slide 16 of 49© People Strategists www.peoplestrategists.com
The objects created by the bean factory are fully configured, ready to use, and aware of their relationships with the other application objects.
The bean factory is involved in managing the life cycle of objects that have been created.
It is represented by the org.springframework.beans.factory.BeanFactory interface.
The most commonly used bean factory is the XML bean factory represented by the org.springframework.beans.factory.xml.XmlBeanFactory
interface.
Introducing Bean Factory
Slide 17 of 49© People Strategists www.peoplestrategists.com
Introducing Bean Factory (Contd.)
XML Bean Factory
Bean configuration file
<?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-3.0.xsd">
...
</beans>
Syntax of a bean configuration file:
Slide 18 of 49© People Strategists www.peoplestrategists.com
Introducing Bean Factory (Contd.)
In a bean configuration file, each bean is defined by using the <bean> tag within the <beans> tag.
A bean definition contains the basic information about a bean that a container must know, such as the process for creating a bean, details about the bean life cycle, and the various dependencies for that bean.
Attributes of <bean> tags are:
id
Used to uniquely identify a bean in
the Spring container.
name
Used to specify an alias name for the
bean.
scope
Used to define the scope of the bean
being defined.
class
Used to specify the fully-qualified
(package name + class name) name of
the bean class.
Slide 19 of 49© People Strategists www.peoplestrategists.com
Introducing Bean Factory (Contd.)
Following code snippet is an example of bean declaration:
Following code snippet displays the class declaration:
<?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-3.0.xsd">
<bean id="Beckham" class="Sport.LAGalaxy"/>
</beans>
package Sport;
public class LAGalaxy implements FootballTeam{
private int squadStrength = 16;
public LAGalaxy(){}
public LAGalaxy (int squadStrength) {
this.squadStrength = squadStrength;
}
public void squadSize(){
System.out.println("LAGalaxy has"+ squadStrength + "players in
its team");
}
}
Slide 20 of 49© People Strategists www.peoplestrategists.com
Introducing Bean Factory (Contd.)
To instantiate a bean factory in your Web application, you first need to load the bean configuration file.
This can be done by using the Resource object, defined by the org.springframework.core.io.Resource interface.
The following table lists the several implementations of the Resourceinterface.
Resource Implementation Function
org.springframework.core.io.ByteAr
rayResourceIt is used for defining a resource whose content is represented as an array of bytes.
org.springframework.core.io.ClassP
athResourceIt is used for defining a resource, retrieved from the specified class path.
org.springframework.core.io.FileSy
stemResourceIt is used for defining a resource, retrieved from the specified file system.
org.springframework.core.io.InputS
treamResourceIt is used for defining a resource, retrieved from an input stream.
org.springframework.web.context.su
pport.ServletContextResourceIt is used for defining a resource, available inside the servlet context.
org.springframework.core.io.UrlRes
ourceIt is used for defining a resource, retrieved from the given URL.
Slide 21 of 49© People Strategists www.peoplestrategists.com
Introducing Bean Factory (Contd.)
The following code snippet loads the bean configuration file, Spring-Config.xml into the Resource object, res:
You can control the number of instances of a particular bean to be created - whether one instance for the entire application or one instance per request.
This is done by defining the scope for the beans.
Bean factory supports the following types of bean scopes:
Singleton: It provides a shared instance of the bean with a particular
name and places it in the factory.
Prototype: It provides a single instance of a bean and guarantees that a
user request will result in the creation of an independent bean for a single
user only.
Resource res =
new ClassPathResource("Sport/Spring-Config.xml");
BeanFactory factory = new XmlBeanFactory(res);
Slide 22 of 49© People Strategists www.peoplestrategists.com
Introducing Bean Factory (Contd.)
Instantiating a bean:
You can retrieve an instance of a bean registered under a given name
from the bean factory by using the getBean()method.
This method takes the ID of the bean as a string value, as shown in the
following code snippet:
When the getBean()method is called, the bean factory container
instantiates the bean and set its properties through DI.
After this, the life of the bean begins inside the Spring container.
LAGalaxy team = (LAGalaxy)
factory.getBean("Beckham");
team.squadSize();
Slide 23 of 49© People Strategists www.peoplestrategists.com
Introducing Bean Factory (Contd.)
Lifecycle of a bean inside the bean factory:
Slide 24 of 49© People Strategists www.peoplestrategists.com
Introducing Application Context
Application Context:
Provides a means for resolving text messages, including support for
internationalization of those messages.
Provides a generic way to load file resources, such as images.
Publishes events to beans, which are registered as listeners.
The following table lists the implementations of the application context container provided by the Spring framework.
Resource Implementation Function
ClassPathXmlApplicationContext It is used to load the bean configuration file located at the specified class path.
FileSystemXmlApplicationContext It is used to load the bean configuration file available in the specified file system.
XmlWebApplicationContext It is used to load the bean configuration file from the location specified by the contextConfigLocationcontext parameter in web.xml. By default, it loads applicationContext.xml stored in the WEB-INFfolder of the Web application.
Slide 25 of 49© People Strategists www.peoplestrategists.com
Introducing Application Context (Contd.)
Loading Application Context:
You can load a application context using any of the three
ApplicationContext implementations.
Example: ClassPathXmlApplicationContext
Example: FileSystemXmlApplicationContext
Example: XmlWebApplicationContext
ApplicationContext appContext = new
FileSystemXmlApplicationContext("c:/Sport/Spring-
Config.xml");
ApplicationContext appContext = new
ClassPathXmlApplicationContext("Sport/Spring-Config.xml");
XmlWebApplicationContext appContext = new
XmlWebApplicationContext();
Slide 26 of 49© People Strategists www.peoplestrategists.com
Introducing Application Context (Contd.)
Life cycle of a bean inside application context:
Slide 27 of 49© People Strategists www.peoplestrategists.com
Task: Creating a Spring Application
Let us see how to create a Spring application.
Slide 28 of 49© People Strategists www.peoplestrategists.com
Sandy has been assigned a task to create the login module for a Web application that can be used to keep track of the product inventory and the orders of the customers. He has to create a Web application by using a framework that makes the business logic components of the application loosely coupled with each other.
Help Sandy in the creation of the Web application structure using an appropriate framework.
Activity: Creating a Web Application with Login
Slide 29 of 49© People Strategists www.peoplestrategists.com
The process of creating and managing association among application objects forms the core of DI and is commonly referred to as wiring.
To inject dependencies into the application objects, you need to configure them in an XML-based configuration file.
In this file, you should first give a definition for the bean for which the dependency is to be created.
Injecting Application Objects
Order
Customer
ProductInjected into
Injected into
Bean wiring
Explicit wiring Autowiring
Slide 30 of 49© People Strategists www.peoplestrategists.com
Applying explicit wiring:
You can explicitly wire the beans by declaring their dependencies in the
configuration file.
While declaring the beans in the configuration file, you can also wire its
properties.
You can explicitly wire the bean properties in the configuration file by
using:
Injecting Application Objects (Contd.)
Setter injection Constructor injection
Slide 31 of 49© People Strategists www.peoplestrategists.com
Using setter injection:
Setter injection is a bean wiring technique in which the JavaBean setter
methods are used for supplying the bean properties to the objects that
need them.
You can wire the bean properties in a Spring-enabled application by
declaring a <property> element for the bean in the configuration file
within the <bean> tag.
The <property> element can inject dependencies using the setter
methods of the property in the following ways:
Injecting Application Objects (Contd.)
Injecting simple values
Referencing other beans
Slide 32 of 49© People Strategists www.peoplestrategists.com
Injecting simple values:
You can use the value attribute of the <property> element to inject a
string value into a bean property.
The value attribute can also take on values of the other types, such as
integer, floating point, and boolean.
Consider an example of Player interface:
The following code snippet declares the FootballBoots interface:
Injecting Application Objects (Contd.)
package SetterInject;
public interface FootballBoots
{
void wearBoots();
}
package SetterInject;
public interface Player
{
void play();
}
Slide 33 of 49© People Strategists www.peoplestrategists.com
The following code snippet implements the Player interface:
Injecting Application Objects (Contd.)
package SetterInject;
public class FootballPlayer implements Player{
public FootballPlayer() {}
@Override
public void play() {
System.out.println("I am playing with " + football +
" football.");
}
private String football;
public void setFootball(String football){
this.football = football;
}
private FootballBoots boots;
public void setBoots(FootballBoots boots){
this.boots = boots;
}
}
Slide 34 of 49© People Strategists www.peoplestrategists.com
The following code snippet does the bean wiring:
Injecting Application Objects (Contd.)
<bean id="Kaka"
class="SetterInject.FootballPlayer">
<property name="football" value="Adidas"/>
</bean>
<bean id="Forlan"
class="SetterInject.FootballPlayer">
<property name="football" value="Nike"/>
</bean>
Slide 35 of 49© People Strategists www.peoplestrategists.com
Referencing other beans:
To wire beans with each other, you have to specify bean references in the
bean configuration file.
You can specify a bean reference for a bean property by using the ref
attribute of the <property> element.
The ref attribute sets the value of the specified property of the bean by
passing to it a reference of another bean.
Consider the following code snippet:
Injecting Application Objects (Contd.)
package SetterInject;
public class Predator implements FootballBoots {
public Predator () {}
public void wearBoots () {
System.out.println("I am wearing Adidas predator
boots.");
}
}
Slide 36 of 49© People Strategists www.peoplestrategists.com
The following code configures the bean:
The following code snippet does the bean wiring:
In the preceding code snippet, the bean uses the predator bean by
referencing it.
Injecting Application Objects (Contd.)
<bean id="predator" class="SetterInject.Predator"/>
<bean id="Kaka"
class="SetterInject.FootballPlayer">
<property name="football" value="Adidas" />
<property name="boots" ref="predator" />
</bean>
<bean id="Forlan"
class="SetterInject.FootballPlayer">
<property name="football" value="Nike" />
<property name="boots" ref="predator" />
</bean>
Slide 37 of 49© People Strategists www.peoplestrategists.com
Using constructor injection:
It is a bean wiring technique, where an object is provided its dependencies
via its own constructors.
The dependencies are passed as arguments of the constructors with each
representing a property or a collaborator object.
In this method, each object declares a constructor or a set of constructors
that take object dependencies as arguments.
Consider the previous example of the Player interface and
FootballPlayer class.
Injecting Application Objects (Contd.)
Slide 38 of 49© People Strategists www.peoplestrategists.com
The FootballPlayer class can be modified as shown in the following
code snippet:
Injecting Application Objects (Contd.)
package SetterInject;
public class FootballPlayer implements Player{
private int shirtNumber;
public FootballPlayer() {}
public FootballPlayer(int shirtNumber){
this.shirtNumber= shirtNumber;
}
@Override
public void play() {
System.out.println("I am playing with shirt number " +
shirtNumber +".");
}
}
Slide 39 of 49© People Strategists www.peoplestrategists.com
The following code snippet wires a bean:
In the preceding code snippet, values are passed as constructor parameter
by making use of the constructor-arg element.
Injecting Application Objects (Contd.)
<bean id="Kaka"
class="SetterInject.FootballPlayer">
<constructor-arg value="7"/>
</bean>
<bean id="Forlan"
class="SetterInject.FootballPlayer">
<constructor-arg value="21"/>
</bean>
Slide 40 of 49© People Strategists www.peoplestrategists.com
Applying autowiring:
The property name or the constructor argument is not declared within the
configuration file.
The Spring container itself finds the type and name of the property and
matches the property type and name with other beans in the container
based on their specified type or name.
In this method, each object declares a constructor or a set of constructors
that take object dependencies as arguments.
Wiring is achieved by setting the autowire property of the beans.
Values of the autowire property are:
byName: Bean is matched whose name matches the name of the property
being wired.
byType: Bean is matched whose type matches the type of the property being
wired.
constructor: Bean is matched based on the parameters of the constructors of
the bean that is being wired.
Injecting Application Objects (Contd.)
Slide 41 of 49© People Strategists www.peoplestrategists.com
autoDetect: Bean is matched first by using constructor, and then byType, if
there is a default constructor with no arguments.
Autowiring by name:
If the name of a property matches the name of the bean that has to be wired
into that property, the Spring framework can automatically wire that bean into
the property.
The following code snippet configures the bean:
The following code snippet wires the bean:
The following code snippet defines the autowiring by name:
Injecting Application Objects (Contd.)
<bean id="boots" class="SetterInject.Predator"/>
<bean id="Kaka"
class="SetterInject.FootballPlayer" autowire="byName">
<property name="football" value="Adidas" />
</bean>
<bean id="Kaka" class="SetterInject.FootballPlayer">
<property name="football" value="Adidas"/>
<property name="boots" ref="predator"/>
</bean>
Slide 42 of 49© People Strategists www.peoplestrategists.com
Autowiring by type:
Spring attempts to find a bean whose type is compatible with the property
type.
The following code snippet defines the autowiring by type:
Injecting Application Objects (Contd.)
<bean id="boots" class="SetterInject.Predator">
</bean>
<bean id="Kaka" class="SetterInject.FootballPlayer"
autowire="byType">
<property name="football" value="Adidas" />
</bean>
Slide 43 of 49© People Strategists www.peoplestrategists.com
Autowiring by constructor:
Is achieved by setting the autowire property to constructor.
Spring automatically selects constructor arguments from the beans, defined in
the configuration file.
Consider the declarartion of RugbyPlayer and RublyBoots classes:
Injecting Application Objects (Contd.)
// code for RugbyPlayer class
package AutowireInject;
public class RugbyPlayer implements Player{
private RugbyBoots rugbyboots;
private int shirtNumber;
public RugbyPlayer(RugbyBoots rugbyboots) {
this.rugbyboots=rugbyboots;
}
public int getShirtNumber() {
return shirtNumber;
}
public void setShirtNumber(int shirtNumber) {
this.shirtNumber = shirtNumber;
}
@Override
public void play() {
Slide 44 of 49© People Strategists www.peoplestrategists.com
The following code snippet does the bean wiring:
Injecting Application Objects (Contd.)
System.out.println("I am playing with shirt number " +
shirtNumber + " and " + rugbyboots.getBoots() +" rugby
boots.");
}}
// code for RugbyBoots class
package AutowireInject;
public class RugbyBoots{
private String boots;
public String getBoots() {
return boots;
}
public void setBoots(String boots) {
this.boots = boots;
}
}
<bean id="Wilkinson"
class="AutowireInject.RugbyPlayer" autowire="constructor">
<property name="shirtNumber" value="7"/>
</bean>
<bean id="NikeBoots" class="AutowireInject.RugbyBoots">
<property name="boots" value="Nike"/>
</bean>
Slide 45 of 49© People Strategists www.peoplestrategists.com
Summary
In this session, you learned that:
Spring aims to minimize the dependency of application code on its framework.
Spring is a modular framework that has the following features:
Pluggability
DI
AOP
Container
Lightweight
The Spring framework has a layered architecture that supports the business logic of a Web application.
Spring is a comprehensive framework that provides you the functionality of several J2EE technologies, such as Struts MVC and EJB, in a single framework.
The Spring framework has a layered architecture made up of seven well-defined modules.
Slide 46 of 49© People Strategists www.peoplestrategists.com
Summary (Contd.)
The seven modules in the Spring framework are:
Spring core module
Spring application context module
Spring Data Access Object (DAO) module
Spring ORM module
Spring AOP module
Spring Web context module
Spring Web MVC module
The core module provides the fundamental functionality of the Spring framework. It contains the most important component of the Spring framework, the bean factory container.
The DAO module of the Spring framework aims to standardize data access work through technologies, such as Hibernate, JDO, or JDBC.
The ORM module enables developers to integrate the Spring framework with several other ORM tools, such as Hibernate, iBatis, and JDO, as required for the application.
Slide 47 of 49© People Strategists www.peoplestrategists.com
Summary (Contd.)
The AOP module enables Spring to provide support for implementing aspects within your Web application.
The MVC module provides a flexible Model-View-Controller implementation for creating Web applications.
The application context module of the Spring framework is built on top of the core module. This module makes Spring a framework and provides you with the ability to obtain application resources for the application objects through a consistent Spring API.
The Web context module of the Spring framework is a part of its Web application development stack, which also includes the MVC module.
The Spring container is based on the concept of DI for managing the application objects.
Slide 48 of 49© People Strategists www.peoplestrategists.com
Summary (Contd.)
The Spring framework provides the following types of containers:
Bean factory
Application context
The bean factory container is used to instantiate, configure, and manage objects (beans) for your application.
It is represented by the org.springframework.beans.factory.BeanFactoryinterface.
The XML bean factory loads the beans on the basis of the bean definitions given in an XML file. This XML file is also called bean configuration file.
The <bean> tag contains the following attributes to define the bean:
id
name
class
scope
Slide 49 of 49© People Strategists www.peoplestrategists.com
Summary (Contd.)
Bean factory supports the following types of bean scopes:
Singleton
Prototype
You can retrieve an instance of a bean registered under a given name from the bean factory by using the getBean() method.
The Spring framework provides the following commonly used implementations of the application context container:
ClassPathXmlApplicationContext
FileSystemXmlApplicationContext
XmlWebApplicationContext
Bean wiring can be done in following ways:
Explicit wiring
Autowiring