Spring Framework
Basics
1
objectives
After the completion of this topic the
participant should be aware of the
following topics
What is spring frame work
Dependency injection
Should be able to work with different wring
2
Topics
What is Spring framework?
Why Spring framework?
Spring framework architecture
Usage scenario
Dependency Injection (DI)
BeanFactory
Autowiring
ApplicationContext
3
What is Spring Framework?
4
What is Spring Framework?
Light-weight yet comprehensive
framework for building Java SE and Java
EE applications
5
What is Spring Framework?
The Spring Framework Mission
Statement
J2EE should be easier to use
It's best to program to interfaces, rather than
classes. Spring reduces the complexity cost of
using interfaces to zero
JavaBeans offer a great way of configuring
applications
OO design is more important than any
implementation technology, such as J2EE
Checked exceptions are overused. A
framework should not force to catch
6
Key Features
JavaBeans-based configuration management,
applying Inversion-of-Control principles,
specifically using the Dependency Injection
technique
This aims to reduce dependencies of components on
specific implementations of other components.
A core bean factory, which is usable globally
Generic abstraction layer for database
transaction management
7
Key Features
Built-in generic strategies for JTA and a single
JDBC DataSource
This removes the dependency on a Java EE
environment for transaction support.
Integration with persistence frameworks
Hibernate, JDO and iBATIS.
MVC web application framework, built on core
Spring functionality, supporting many
technologies for generating views, including
JSP, FreeMarker, Velocity, Tiles, iText, and POI.
8
Key Features
Extensive aspect-oriented programming
(AOP) framework to provide services
such as transaction management
As with the Inversion-of-Control parts of
the system , this aims to improve the
modularity of systems created using the
framework.
9
Why Use
Spring Framework?
10
Why Use Spring?
Wiring of components through
Dependency Injection
Promotes de-coupling among the parts that
make the application
Design to interfaces
Insulates a user of a functionality from
implementation details
Test-Driven Development (TDD)
POJO classes can be tested without being
tied up with the framework
11
Why Use Spring?
Declarative programming through AOP
Easily configured aspects, esp. transaction
support
Simplify use of popular technologies
Abstractions insulate application from
specifics, eliminate redundant code
Handle common error conditions
Underlying technology specifics still
accessible
12
Why Use Spring?
Conversion of checked exceptions to
unchecked
(Or is this a reason not to use it?)
Not an all-or-nothing solution
Extremely modular and flexible
Well designed
Easy to extend
Many reusable classes
13
Why Use Spring?
Integration with other technologies
EJB for J2EE
Hibernate, iBates, JDBC (for data access)
Velocity (for presentation)
Struts and WebWork (For web)
14
Spring software
You can download the Spring distribution
from Spring’s website:
http://www.springframework.org.
Choose the downloads link from the left-
hand menu and look for the Spring 2.5
download.
Download spring-framework-2.5-with-
dependencies.jar file
15
Some of the spring jars
spring.jar Contains most of the modules of the Spring Framework
in one convenient JAR file.
spring-aspects.jar Spring’s AspectJ-specific classes.
spring-aop.jar The Spring AOP module.
spring-beans.jar The Spring bean factory module.
spring-core.jar Classes that are core to the Spring Framework.
spring-dao.jar The basis for Spring’s DAO support.
spring-hibernate3.jar Hibernate 3 support
spring-jdbc.jar Spring jdbc module
spring-webmvc.jar Spring’s web application context and utilities.
spring-web.jar Spring mvc module
16
Spring Framework
Architecture
17
Spring Framework
18
Core Package
Core package is the most fundamental part of
the framework and provides the IoC and
Dependency Injection features
The basic concept here is the BeanFactory,
which provides a sophisticated implementation
of the factory pattern which removes the need
for programmatic singletons and allows you to
decouple the configuration and specification of
dependencies from your actual program logic
19
DAO Package
The DAO package provides a JDBC-
abstraction layer that removes the need
to do tedious JDBC coding and parsing
of database-vendor specific error codes
The JDBC package provides a way to do
programmatic as well as declarative
transaction management, not only for
classes implementing special interfaces,
but for all your POJOs (plain old Java
objects)
20
ORM Package
The ORM package provides integration
layers for popular object-relational
mapping APIs, including JPA, JDO,
Hibernate, and iBatis.
Using the ORM package you can use all
those O/R-mappers in combination with
all the other features Spring offers, such
as the simple declarative transaction
management feature mentioned
previously
21
AOP Package
Spring's AOP package provides an AOP
Alliance-compliant aspect-oriented
programming implementation allowing you to
define, for example, method-interceptors and
pointcuts to cleanly decouple code
implementing functionality that should logically
speaking be separated
Using source-level metadata functionality you
can also incorporate all kinds of behavioral
information into your code
22
MVC Package
Spring's MVC package provides a
Model-View-Controller (MVC)
implementation for webapplications
Spring's MVC framework is not just any
old implementation; it provides a clean
separation between domain model code
and web forms, and allows you to use all
the other features of the Spring
Framework.
23
Usage Scenarios
24
Usage Scenarios
You can use Spring in all sorts of
scenarios, from applets up to fully-
fledged enterprise applications using
Spring's transaction management
functionality and web framework
integration
25
Typical Full-fledged Spring Web
Application
26
Spring Middle-tier Using 3rd party
Web Framework
27
Remoting Usage Scenario
28
EJBs – Wrapping Existing POJOs
29
Dependency Injection (DI):
Basic concept
30
Spring Dependency Injection
A kind of Inversion of Control (IoC)
“Hollywood Principle”
Don't call me, I'll call you
“Container” resolves (injects) dependencies of
components by setting implementation object
(push)
As opposed to component instantiating or Service
Locator pattern where component locates
implementation (pull)
Martin Fowler calls Dependency Injection
31
Benefits of Dependency Injection
Flexible
Avoid adding lookup code in business logic
Testable
No need to depend on external resources or
containers for testing
Maintainable
Allows reuse in different application environments by
changing configuration files instead of code
Promotes a consistent approach across all
applications and teams
32
Two Dependency Injection Variants
Constructor dependency Injection
Dependencies are provided through the
constructors of the component
Setter dependency injection
Dependencies are provided through the
JavaBean style setter methods of the
component
More popular than Constructor dependency
injection
33
Constructor Dependency Injection
public class ConstructorInjection {
private Dependency dep;
public ConstructorInjection(Dependency
dep) {
this.dep = dep;
}
}
34
Setter Dependency Injection
public class SetterInjection {
private Dependency dep;
public void setMyDependency(Dependency
dep) {
this.dep = dep;
}
}
35
Dependency Injection (DI):
DI Support in Spring
36
Sub-topics
BeanFactory interface
XmlBeanFactory implementation
Bean configuration file
Setter dependency injection
Constructor dependency injection
Beans
Injection parameters
37
BeanFactory
BeanFactory object is responsible for
managing beans and their dependencies
Your application interacts with Spring's DI
container through BeanFactory interface
BeanFactory object has to be created by the
application typically XmlBeanFactory
BeanFactory object, when it gets created, read bean
configuration file and performs the wiring
Once created, the application can access the beans
via BeanFactory interface
38
BeanFactory Implementations
XmlBeanFactory
Convenience extension of
DefaultListableBeanFactory
that reads bean definitions from an XML
document
39
Reading XML Configuration File via
XmlBeanFactory class
public class XmlConfigWithBeanFactory {
public static void main(String[] args) {
XmlBeanFactory factory =
new XmlBeanFactory(new FileSystemResource("beans.xml"));
SomeBeanInterface b =
(SomeBeanInterface) factory.getBean(“nameOftheBean”);
}
}
40
Bean Configuration File
Each bean is defined using <bean> tag under the
root of the <beans> tag
The id attribute is used to give the bean its default
name
The class attribute specifies the type of the bean
41
Bean Configuration File Example
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="renderer" class="StandardOutMessageRenderer">
<property name="messageProvider">
<ref local="provider"/>
</property>
</bean>
<bean id="provider" class="HelloWorldMessageProvider"/>
</beans>
42
Wiring a Bean
43
Beans
The term “bean” is used to refer any
component managed by the BeanFactory
The “beans” are in the form of JavaBeans (in
most cases)
no arg constructor
getter and setter methods for the properties
Beans are singletons by default
Properties the beans may be simple values or
references to other beans
Beans can have multiple names
44
What is Wiring?
The act of creating associations between
application components is referred to as
wiring
There are many ways to wire a bean but
common approach is via XML
45
Wiring example
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="greetBean“ class="GreetingServiceImpl">
<property name="greeting">
<value>Hello friends of Spring</value>
</property>
</bean>
</beans>
46
Wiring the beans
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
The root element
<beans>
<bean id=“mybean“ class=“com.jp.TestBean">
</bean>
</beans>
bean’s id
Bean instance
(beans class name)
47
Wiring the beans
Prototype and Singleton beans
all spring beans are singleton
but prototype beans can also be defined
<bean id =“myBean” class=“com.jp.TestBean”
singleton=“false”/>
singleton = “false” returns a prototype bean
singleton = “true” returns a singleton bean
default value for “singleton” is “true”
48
Wiring the beans
Initialization and Destruction
beans can be initialized and destroyed by
calling bean specific methods
init-method : calls bean specific initialization
method
destroy-method : calls bean specific cleanup
method
49
Wiring the beans
Initialization and Destruction (example)
public class MyConnectionPool {
public void initialize(){
//initialize a connection;
}
public void cleanup() {
//release connection;
}
}
configuration:
<bean id=“myBean” class =“com.jp.MyConnectionPool”
init-method=“initialize” destroy-method=“cleanup” />
50
Spring Dependency Injection
Revisted….
Two types of Dependency Injection
setter injection
dependency injected via setter methods
constructor injection
dependency injected via constructor
51
Spring Dependency Injection
Setter Injection
<bean id=“test” class=“com.jp.TestBean”>
<property name=“greeting”>
<value>Hello friends</value>
</property>
</bean> Set the greet property by
calling setGreeting( “Hello Friends” )
52
Spring Dependency Injection
Referencing other beans
<beans>
<bean id=“test” class =“com.jp.TestBean”>
<property name=“greeting”>
<ref bean=“greetBean”/>
</property>
<bean id=“greetBean” class =“com.jp.GreetBean” />
<beans>
53
Spring Dependency Injection
Constructor Injection
<bean id=“test” class=“com.jp.testBean”>
<constructor-arg>
<value>Hello friends</value>
</constructor-arg>
constructs a TestBean
</bean>
object through
its constructor
<bean id=“test” class=“com.jp.testBean”>
<constructor-arg>
<ref bean=“greetBean”/>
</constructor-arg>
</bean>
54
Wiring Collections
Spring supports Many types of Collections as
bean properties
Supported types are:
XML Types
<list> java.util.List, arrays
<set> java.util.Set
<map> java.util.Map
<props> java.util.Properties
55
Dependency Injection:
Autowiring
56
Auto Wiring
So far we wired beans explicitly using
<property> tag
Spring can also do Wiring automatically
<bean id="foo" class="com.jp.spring.Foo“
autowire= "autowire
type"/>
57
Autowiring Properties
Beans may be auto-wired (rather than using <ref>)
Per-bean attribute autowire
Explicit settings override
autowire=“name”
Bean identifier matches property name
autowire=“type”
Type matches other defined bean
autowire=”constructor”
Match constructor argument types
autowire=”autodetect”
Attempt by constructor, otherwise “type”
58
ApplicationContext
59
What is ApplicationContext?
Extension of BeanFactory
It provides all the same functionality and more
Reduces the amount of code you need
In a more framework-oriented style
Add new features over BeanFactory
Resource management and access
Additional life-cycle interfaces
Improved automatic configuration of infrastructure
components
Event publication
Internationalization
60
When to Use ApplicationContext?
Use ApplicationContext over
BeanFactory to take advantage of its
extended functionality
Except for a few limited situations such as
perhaps in an Applet, where memory
consumption might be critical, and a few
extra kilobytes might make a difference
61
Using MessageSource
The ApplicationContext interface extends an interface
called MessageSource, and therefore provides messaging
(i18n or internationalization)functionality
<beans>
<bean id="messageSource”
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>format</value>
</list>
</property>
</bean>
</beans>
62
Propagating Events
Event handling in the
ApplicationContext is provided through
the ApplicationEvent class and
ApplicationListener interface
If a bean which implements the
ApplicationListener interface is deployed into
the context, every time an ApplicationEvent
gets published to the ApplicationContext,
that bean will be notified
Essentially, this is the standard Observer
design pattern.
63
Three Built-in Events
ContextRefreshEvent
ApplicationContext is initialized or refreshed
ContextClosedEvent
ApplicationContext is closed
RequestHandleEvent
A web-specific event telling all beans that a
HTTP request has been serviced
64
Example: Event Handling
Configuration
<bean id="emailer" class="example.EmailBean">
<property name="blackList">
<list>
<value>[email protected]</value>
<value>[email protected]</value>
<value>[email protected]</value>
</list>
</property>
</bean>
<bean id="blackListListener" class="example.BlackListNotifier">
<property name="notificationAddress" value="[email protected]"/>
</bean>
65
Example: Event Handling
Notifier class
public class BlackListNotifier implement ApplicationListener {
/** notification address */
private String notificationAddress;
public void setNotificationAddress(String notificationAddress) {
this.notificationAddress = notificationAddress;
}
public void onApplicationEvent(ApplicationEvent evt) {
if (evt instanceof BlackListEvent) {
// notify appropriate person
}
}
}
66
Property place holder configurer
<bean id="ppropertyConfigurer"
class="org.springframework.beans.factory.conf
ig.PropertyPlaceholderConfigurer">
<property name="location"
value="trainingtext1.properties"></property>
</bean>
<bean id="mb" class="com.jp.MyBean">
<property name="fname" value="$
{afname}"></property>
</bean>
67
How to use ApplicationContext?
Many users will use ApplicationContext
in a completely declarative fashion, not
even having to create it manually, but
instead relying on support classes such
as ContextLoader to automatically start
an ApplicationContext as part of the
normal startup process of a J2EE
webapp
it is still possible to programmatically create
an ApplicationContext
68
Spring ApplicationContext
A Spring ApplicationContext allows you to get access
to the objects that are configured in a BeanFactory in
a framework manner.
ApplicationContext extends BeanFactory
Adds services such as international messaging
capabilities.
Add the ability to load file resources in a generic fashion.
Several ways to configure a context:
XMLWebApplicationContext – Configuration for a web
application.
ClassPathXMLApplicationContext – standalone XML
application context
FileSystemXmlApplicationContext
Allows you to avoid writing Service Locators
69
Summary
Using dependency injection we can
inject the dependencies into our
application
IOC reduces the programmers burden
Different types of wring gives us more
flexibility
70