© 2008 coreservlets.com
The Spring Framework:
The Spring Framework:
Core Capabilities Part 1
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/spring.html
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.
© 2008 coreservlets.com
For live Spring & Hibernate training, see
t htt //
l t
/
courses at http://courses.coreservlets.com/.
Taught by the experts that brought you this tutorial.
Available at public venues or customized versions
Available at public venues, or customized versions
can be held on-site at your organization.
C d l d d t ht b M t H ll
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
•Courses developed and taught by Marty Hall
–Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics
•Courses developed and taught by coreservlets.com experts (edited by Marty)
Topics in This Section
p
•
Spring IoC container
•
Interface-oriented development
•
Spring framework composition
•
Spring container instantiation
•
Spring bean definitions
Java EE training: http://courses.coreservlets.com
4
© 2008 coreservlets.com
S i
I C C
t i
Spring IoC Container
p
g
•
Fundamental features
–
Registration system (
applicationContext.xml
)
•
Complex initialization
•
Object creation
j
•
Dependency injection
•
Application configuration
Access API
Java EE training: http://courses.coreservlets.com
–
Access API
• BeanFactory#getBean
6
Spring IoC Container Relevance
p
g
•
Inversion of control
–
Moves object creation and dependency resolution
responsibilities out of business logic
–
Enables business logic to be portable
–
Enables business logic to be portable
–
Allows components to be reconfigured with minimal
effort
•
Loose coupling
–
Clients are insulated from implementations
I
l
i
h i li i
i i ibl
li
–
Implementation technicalities are invisible to clients
–
Clients are only aware of the interface contract and
unaware of:
u awa e o :
•
Concrete type selections
Spring IoC Container and POJO
Instantiation
Instantiation
•
Integrate Spring IoC container
–
Replace custom ServiceProviderFramework with
BeanFactory
•
Delegate to Spring IoC container
•
Delegate to Spring IoC container
–
Object creation
Java EE training: http://courses.coreservlets.com
8
Spring IoC Objective
p
g
j
•
Create a
BookLibrary
object based on the
l
Spring IoC Process
p
g
•
Create an XML file conforming to
spring beans xsd
spring-beans.xsd
–
Name the file
• Conventional name is applicationContext.xml
H ill ffi
• However, any name will suffice
–
Place the file in an accessible location
• For example, in a filesystem directory which will be accessible from the classpath
classpath
–
Register objects
• Objects are registered by declaring beanXML elements
• Conventional approach is to useConventional approach is to use beanbeanattributes:attributes: ididandand classclass
•
Access object(s) managed by the Spring IoC container
– Instantiate a BeanFactoryimplementation
Use interfaces such asBeanFactory#getBean( ):Object
Java EE training: http://courses.coreservlets.com
– Use interfaces such as BeanFactory#getBean(...):Object
10
Spring IoC Configuration
p
g
g
•
Object registration process
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"p // g/ /
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="bookLibrary" class="coreservlets.JavaBookLibrary"/>
</beans>
Spring IoC BeanFactory
p
g
y
import org.springframework.beans.factory.*; import org.springframework.context.support.*;p g p g pp ;
public class Main {
public static void main(String[] args) {
BeanFactory beanFactory =
new ClassPathXmlApplicationContext( "/applicationContext.xml");
Spring BeanFactory configuration
BookLibrary service =
(BookLibrary)beanFactory.getBean("bookLibrary");
Spring BeanFactory access API
System.out.printf("Retrieved BookLibrary type: \"%s\"%n", service.getClass().getSimpleName());
}
Standard output Interface type
Java EE training: http://courses.coreservlets.com
}
12
Standard output
Retrieved BookLibrary type: "JavaBookLibrary"
Interface type
Spring IoC Container Summary
p
g
y
•
Loaded
B
d fi i i
f
li
i
l
–
Bean definitions from
applicationContext.xml
•
Created
–
coreservlets.JavaBookLibrary
instance
•
Registered
–
Object under the name
bookLibrary
Requested
•
Requested
–
A
BookLibrary
object from the Spring IoC container using the
access API,
BeanFactory#getBean(…)
•
Received
–
An instance of
JavaBookLibrary
, a
BookLibrary
Model Analysis
y
•
Dynamic implementation choices
–
Implementation types are excluded from the program
•
Portable model configuration
Obj
d l
fi
i
i
l
d i hi h
–
Object model configuration is encapsulated within the
framework
•
Flexible model configuration
Flexible model configuration
–
Object model configuration is a declarative system based
on
spring-beans.xsd
Java EE training: http://courses.coreservlets.com
14
Spring IoC Container and
Dependency Injection
Dependency Injection
•
Delegate to Spring IoC container
–
Object instantiation
Spring IoC Objective
p
g
j
•
Create a
BookLibrary
object based on the
J
B
kLib
class
JavaBookLibrary
class
•
Create a
BookReader
object based on the
BookReader
class
•
Inject the
BookLibrary
object into
BookReader
Java EE training: http://courses.coreservlets.com
16
Spring Process
p
g
•
Create an XML file conforming to
spring beans xsd
spring-beans.xsd
–
Name the file
–
Place the file in an accessible location such as the classpath
–
Register objects using XML
beanelements
–
Add bean dependency injection instructions
•
Add references to beans values collections or
•
Add references to beans, values, collections, or
configuration properties
•
Also known as “wiring” the application
Access object(s) managed by the Spring IoC container
•
Access object(s) managed by the Spring IoC container
– Instantiate a BeanFactoryimplementation
Spring XML Configuration
p
g
g
•
Object registration process
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"p // g/ /
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> Referenceable bean
<bean id="bookLibrary" class="coreservlets.JavaBookLibrary"/>
<bean id="bookReader" class="coreservlets.BookReader">
<constructor-arg ref="bookLibrary"/>
</bean>
</beans>
Bean reference
Java EE training: http://courses.coreservlets.com
</beans>
18
BookReader Constructor
public class BookReader { public class BookReader {
private BookLibrary bookLibrary;
public BookReader(BookLibrary bookLibrary) { this.bookLibrary = bookLibrary;
}
public List<Book> read() {
List<Book> books = bookLibrary.search("Java"); for(Book book : books){
Dependency injection interface
System.out.printf("Reading: %s%n", book); }
return books; }
Spring BeanFactory
p
g
y
public class Main {
public static void main(String[] args) { public static void main(String[] args) {
BeanFactory beanFactory =
new ClassPathXmlApplicationContext(
Spring BeanFactory configuration
"/applicationContext.xml");
BookReader client = (BookReader) beanFactory getBean("bookReader");
Spring BeanFactory access API
beanFactory.getBean( bookReader );
List<Book> books = client.read();
System.out.printf("Client read: %s books%n", books.size()); }
} Standard output
Java EE training: http://courses.coreservlets.com
20
Reading: Core Servlets and JavaServer Pages Reading: More Servlets and JavaServer Pages Client read: 2 books
Spring IoC Container Summary
p
g
y
•
Loaded
d fi i i
f
–
Bean definitions from
applicationContext.xml
•
Created
–
coreservlet JavaBookLibrary
coreservlet.JavaBookLibrary
instance
instance
–
coreservlet.BookReader
instance
•
Registered
g
–
Object under the name
bookLibrary
–
Object under the name
bookReader
I j t d d
d
•
Injected dependency
–
BookLibrary
implementation instance,
Spring IoC Container Summary
Continued
Continued
•
Requested
A
bj
f
h S i
C
i
–
A
BookReader
object from the Spring IoC container
using the access API,
BeanFactory#getBean(…)
•
Received
Received
–
An instance of
BookReader
•
Used
–
The
BookLibrary
dependency was previously fulfilled
during the injection step
–
BookReader
BookReader
used
used
BookLibrary
BookLibrary
interfaces to access
interfaces to access
and read
Book
information
Java EE training: http://courses.coreservlets.com
22
Model Analysis
y
•
Dynamic implementation choices
–
Implementation types are excluded from the program
–
Decoupled design allows new types to be configured into
the program without having to recompile
the program without having to recompile
•
Portable model configuration
–
Object model configuration is encapsulated within the
O j
g
p
framework
•
Flexible model configuration
–
Object model configuration is a declarative system based
on
spring-beans.xsd
–
BeanFactory
BeanFactory
clients are also decoupled from the bean
clients are also decoupled from the bean
© 2008 coreservlets.com
Interface-Oriented
Interface Oriented
Development
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.
Interface-Oriented Development
p
•
Take advantage of type-polymorphism
–
Flexible architecture
–
Tolerant to changes
Enables new capabilities with minimal effort
–
Enables new capabilities with minimal effort
•
Commit to interfaces, not implementations
–
Included but not limited to compiled interactions
Included, but not limited to, compiled interactions
Interface-Oriented Example
p
<bean id="bookLibrary"
class="coreservlets.JavaBookLibrary"/>y
<bean id="bookReader"
class="coreservlets.BookReader" >
<constructor arg ref "bookLibrary"/> Interface type <constructor-arg ref="bookLibrary"/>
</bean>
public class BookReader {
private BookLibrary bookLibrary;
public BookReader(BookLibrary bookLibrary) { this.bookLibrary = bookLibrary;
}
Java EE training: http://courses.coreservlets.com
... }
Interface-Oriented Example
p
<bean id="bookLibrary"
class="coreservlets.JavaBookLibrary" /> class= coreservlets.JavaBookLibrary />
Interface type
public class Main {
public static void main(String[] args) {
Interface type
...
BookLibrary service =
(BookLibrary)beanFactory.getBean("bookLibrary");
Service Abstraction
•
Abstract elements such as third-party APIs
d i f
and infrastructure
•
Decouple business logic enabling
portability
portability
Java EE training: http://courses.coreservlets.com
© 2008 coreservlets.com
S i
F
k
Spring Framework Composition
p
g
p
•
IoC Container
–
Core libraries
•
spring-core
•
spring-beans
spring beans
–
Integration extensions
•
spring-context
i
b
•
spring-web
Java EE training: http://courses.coreservlets.com
30
Spring Framework
Modules
Modules
•
Aspect-Oriented Programming
–
spring-aop
•
Service abstractions
JDBC templates and transaction management
–
JDBC templates and transaction management
•
spring-jdbc
•
spring-tx
–
O/R mapping frameworks
•
spring-orm
–
JMS
•
spring-jms
–
JEE, EJB, JMX, JNDI, etc…
•
spring-context
•
spring-context
Spring Framework Composition
p
g
p
•
Test support
–
TestNG and JUnit, IoC container, and transaction
management integration
•
spring-test
spring test
•
Web Application Framework
–
Spring Web MVC, FreeMarker, and Jasper Reports
p
g
p
p
•
spring-webmvc
Java EE training: http://courses.coreservlets.com
32
© 2008 coreservlets.com
S i
BeanFactoryy
•
BeanFactory
–
Defines core but non-specific
functionality
ApplicationContext
•
ApplicationContext
–
Context resources
–
Bundle resources
Bundle resources
–
Event listeners
–
Post processors
Java EE training: http://courses.coreservlets.com
34
Coarse-Grained Interfaces
•
Covers typical integration scenarios
•
Automated but implicit functionality
•
Committed to specific integration strategies
BeanFactory beanFactory =
new ClassPathXmlApplicationContext( "/applicationContext.xml");
BeanFactory beanFactory =
Fine-Grained Interfaces
•
Fine integration control
–
Bean configuration abstraction
–
I/O abstraction
BeanFactory beanFactory =
new GenericApplicationContext();
Parses and loads bean definitions
I t ti ith i I/O i t f
XmlBeanDefinitionReader xmlReader =
new XmlBeanDefinitionReader(beanFactory);
Integration with generic I/O interfaces
Integration with spring I/O abstractions
xmlReader.loadBeanDefinitions(
new FileInputStream("/etc/applicationContext.xml"));
i i i
Integration with spring I/O abstractions
Java EE training: http://courses.coreservlets.com
xmlReader.loadBeanDefinitions(
new ClassPathResource("/applicationContext.xml"));
36
Servlet Integration
g
<web-app>
<context-param> <context param>
<param-name>contextConfigLocation</param-name> <param-value>
WEB-INF/applicationContext.xml classpath:/applicationContext.xml </param-value>
</context-param>
<listener> E l f S i <listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener </listener-class>
Example of Spring resource abstraction
JavaServer Faces Integration
g
•
Multiple variable and EL resolver
i
l
i
implementations
–
JSF 1.1
•
DelegatingVariableResolver
•
DelegatingVariableResolver
•
SpringBeanVariableResolver
–
JSF 1.2
•
SpringBeanFacesELResolver
<faces-config> <application> <application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver </variable-resolver>
Java EE training: http://courses.coreservlets.com
</application> </faces-config>
38
JUnit Test Integration
g
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration
@ContextConfiguration
public class BookLibraryTest {
@Autowired Loads bean definitions
defaults to applicationContext.xml JUnit integration
public BookLibrary bookLibrary;
@Test
public void verifySearch(){ }
defaults to applicationContext.xml
public void verifySearch(){ ... }
}
Loads bean definitions using explicit paths
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext.xml"}) public class BookLibraryTest {
JUnit Test Integration
g
@ContextConfiguration
public class BookLibraryTest public class BookLibraryTest
extends AbstractJUnit4SpringContextTests {
@Autowired
public BookLibrary bookLibrary;
@Test
public void verifySearch(){ ...
} } }
Java EE training: http://courses.coreservlets.com
40
Container Event Listener
•
Lifecycle event model
–
Event listener interface
org.springframework.context.ApplicationListener
–
Event objects
ve objec s
org.springframework.context.ApplicationEvent • ContextRefreshEvent
• ContextStartedEvent • ContextStoppedEvent • ContextClosedEvent • RequestHandledEvent
•
Registration model
–
Enabled by registering new listener instances as
t i
d b
Container Event Listener
Example
Example
import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;public class SimpleApplicationListener implements ApplicationListener {
public void onApplicationEvent(ApplicationEvent event) { System.out.printf("Event type: %s%n",
event getClass() getSimpleName()); event.getClass().getSimpleName()); } } <beans> <bean id="applicationListener" class="coreservlets.SimpleApplicationListener" /> /b
Java EE training: http://courses.coreservlets.com
</beans>
42
Container Event Listener
Example
Example
import org.springframework.beans.factory.*; import org.springframework.context.*;
import org.springframework.context. ;
import org.springframework.context.support.*; public class Main {
public static void main(String[] args) {
Instantiate container
BeanFactory beanFactory = new ClassPathXmlApplicationContext(
"/applicationContext.xml");
Expose interfaces for triggering lifecycle events
ConfigurableApplicationContext configurableContext = (ConfigurableApplicationContext) beanFactory;
configurableContext.start();
T i lif l
configurableContext.stop(); configurableContext.close(); }
}
Trigger lifecycle events
Standard output
Event type: ContextRefreshedEvent } Event type: ContextRefreshedEvent
© 2008 coreservlets.com
Bean Definition
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.
Bean Definitions
•
Default bean definition
•
Factory bean
Default Bean Definition
•
Create container-managed objects directly out of
bean elements
bean elements
–
Standard bean definitions:
•
XML
bean
element. Child to document root,
,
bean
–
Inner bean definitions
•
XML
bean
element. Child to
property or
constructor-arg
elements
constructor arg
elements
Java EE training: http://courses.coreservlets.com
46
Default Bean Definition
•
Standard
bean
element
–
Referenceable, aka collaborator, beans
•
Inner bean
A
–
Anonymous
–
Prototype
–
Used to fulfill dependency injection settings
Used to fulfill dependency injection settings
•
Invocation prerequisite(s)--one combination
required
q
–
class
–
class
and
factory-method
d
–
factory-bean
and
factory-method
Default Bean Definition
•
Optional
bean
properties
–
id
and
name
•
defaults to a generated and unique value
–
scope
scope
•
defaults to
singleton
–
abstract/lazy-init/primary
•
defaults to false
–
autowire
•
defaults to no
–
dependency-check
– defaults to none
–
parent/depends-on/autowire-candidate/init-method/destroy method
Java EE training: http://courses.coreservlets.com
method/destroy-method
•
defaults to
null
48
Standard
bean
•
Matches on a
Constructor
–
See java.lang.Class and java.lang.reflect
•
Invokes the
Constructor
Analogous to the
new
keyword invoking a
Constructor
is
–
Analogous to the
new
keyword, invoking a
Constructor
is
the same as invoking the
new
operator
<bean id="bookLibrary" <bean id= bookLibrary
class="coreservlets.JavaBookLibrary"> <!-- empty constructor arguments -->
</bean>
C d fi i i
public class JavaBookLibrary { public JavaBookLibrary() {
...
Constructor definition
Standard
bean
•
Matches on a
Constructor
by type
<bean id="bookLibrary"
class="coreservlets.JavaBookLibrary"> </bean>
</bean>
<bean id="bookReader" class="coreservlets.BookReader" >
t t f "b kLib "/
Bean aka collaborator
<constructor-arg ref="bookLibrary"/> </bean>
public class BookReader { Constructor definition
p
private BookLibrary bookLibrary;
public BookReader(BookLibrary bookLibrary) { this.bookLibrary = bookLibrary;
}
& bean reference
Java EE training: http://courses.coreservlets.com
} ... }
50
Constructor target
Inner
bean
Element
•
Nested bean definitions
<bean id="bookReader" class="coreservlets.BookReader" > <constructor-arg>
<bean class="coreservlets JavaBookLibrary"/> <bean class= coreservlets.JavaBookLibrary /> </constructor-arg>
</bean>
Anonymous inner bean
public class BookReader {
private BookLibrary bookLibrary;
public BookReader(BookLibrary bookLibrary) { this bookLibrary = bookLibrary;
Constructor definition
this.bookLibrary = bookLibrary; }
... }
Factory Bean
y
•
The invocation of a method on a
container-d f
b
h
managed factory bean to create other
container-managed beans
References to the target bean class are
•
References to the target bean class are
excluded
–
The class information for the target bean is unnecessary
The class information for the target bean is unnecessary
Java EE training: http://courses.coreservlets.com
52
Factory Bean
y
•
Factory bean
A
i
d b
ibl f i
i i
h
–
A container-managed bean responsible for instantiating other
container-managed beans
–
Referenced by a bean
element attribute, factory-bean
•
Factory method
–
The factory bean exposes a method for instantiating the target
bean type
bean type
–
Referenced by a
bean
element attribute,
factory-method
•
Target bean
–
The
bean
declaration uses
factory-bean
and
factory-method
to map its origin to the factory bean and factory
Factory Bean Example
y
p
public class BookLibraryFactory { public BookLibrary newInstance() {
p y () {
return new JavaBookLibrary(); }
}
Factory class Factory method
<bean id="bookLibraryFactory"
class="coreservlets.BookLibraryFactory"/>
Factory bean
<bean id="bookLibrary"
factory-bean="bookLibraryFactory" factory-method="newInstance" />
F t b f Factory method
Factory bean reference
Java EE training: http://courses.coreservlets.com
54
Static Factory Method
y
•
The invocation of a static factory method to
h
i
d b
create the container-managed bean
•
Separate container-managed bean is not
required
required
•
The target bean references the class and
method information as the origin
Static Factory Method Example
y
p
public class BookLibraries {
public static BookLibrary newInstance() { public static BookLibrary newInstance() {
return new JavaBookLibrary(); }
}
Static factory method
<beans>
<bean id="bookLibrary"
class="coreservlets.BookLibraries" factory-method="newInstance"/> </beans>
S i f h d Class defining factory method
Static factory method
Java EE training: http://courses.coreservlets.com
56
Abstract Bean
•
Bean templating facility
•
Establishes default bean properties
–
Constructor arguments, property setter parameters, bean
lifecycle callbacks
lifecycle callbacks
•
Candidate classes for abstract bean
definitions
definitions
Abstract Bean Example
p
<bean id="dataSourceTemplate" abstract="true"> <property name="url" value="jdbc:shinydb:" /> <property name url value jdbc:shinydb: />
<property name="driver" value="jdbc.ShinyDriver" /> <property name="username" value="webapp" />
</bean>
<bean id="dataSource" class="DriverManagerDataSource"> parent="dataSourceTemplate">
<property name="password" value="orioles" /> <property name= password value= orioles /> </bean>
Abstract discriminator
Template bean reference
Java EE training: http://courses.coreservlets.com
58
© 2008 coreservlets.com
W
Wrapup
Customized Java EE Training: http://courses.coreservlets.com/
General Approach
pp
•
Develop POJOs
–
Implement creational patterns as needed
–
Assume the framework will accommodate the
ti
l
tt
i d b th
t
creational patterns required by the system
•
Plan on using a framework to manage the
instantiation of all POJOs
instantiation of all POJOs
•
Create the XML bean definitions file
This file is typically named
–
This file is typically named
applicationContext.xml
–
For large projects comprised of numerous modules,
Java EE training: http://courses.coreservlets.com
o a ge p ojects co p sed o u e ous odu es,
develop a predictable naming system for context files
60
General Approach (Continued)
pp
(
)
•
Declare bean definitions with
interdependencies
–
Spring IoC provides comprehensive support for
i t ti ti
tt
instantiation patterns
•
Constructor
•
Factory method
y
•
Static factory method
•
Template beans
I
l d th b
d fi iti
fil
t f
•
Include the bean definitions file as part of
the distribution
Thi fil
ill
d f lt b t
ti
l
Summaryy
•
Select a Spring IoC container integration
approach to match the runtime context
–
Broad integration options are available
P
ti
t t
•
Programmatic contexts
– ClassPathXmlApplicationContext
– FileSystemXmlApplicationContext
•
Platform-specific contexts
– ContextLoaderListener
•
Test contexts
– AbstractJUnit4SpringContextTests
–
ApplicationContext is favored over BeanFactory
implementations
Java EE training: http://courses.coreservlets.com
implementations
•
Improved defaults, integration extensions, and
automated behavior
62
© 2008 coreservlets.com
Q
ti
?
Questions?
Customized Java EE Training: http://courses.coreservlets.com/