Basic of Spring Framework

Download Report

Transcript Basic of Spring Framework

Basics of
SPRING FRAMEWORK
July 27, 2008
1
Spring Framework
Agenda
Basics
Introduction to IoC and AOP
Spring Core
AOP in Detail
Bean Lifecycle
Extensibility
Spring - The Beginning…
References
Questions/Feedback
July 27, 2008
2
Spring Framework
01 Basics
July 27, 2008
3
Spring Framework
Spring?
Spring is a Lightweight, Inversion of Control and AspectOriented Container Framework
Lightweight
Inversion of Control
Aspect Oriented
Container
Framework
July 27, 2008
4
Spring Framework
Spring Goals
Play role in Enterprise Application Architecture
Core Support
Web Application Development Support
Enterprise Application Development Support
Spring Triangle
July 27, 2008
5
Spring Framework
Spring Triangle
Enterprise Service Abstractions
July 27, 2008
6
Spring Framework
Spring Objectives
To make J2EE easier to use and promote EBP
Always better to program to interfaces than classes
JavaBeans are a great way to configure applications
Framework should not force to catch exceptions if one is
unlikely to recover from them
Testing is essential and framework should make it easier
To make integration with existing technologies easier
To easily integrate in existing projects
July 27, 2008
7
Spring Framework
Spring Advantages
Organizes middle tier objects
Eliminates proliferation of singletons
Spring is mostly non-intrusive*
Applications built on Spring are easy to Unit Test
Use of EJB becomes an implementation choice
Consistent framework for Data Access whether JDBC or
O/R mapping
Any part of Spring can be used in isolation.
Provides for flexible architecture
Benefit to all application layers
July 27, 2008
8
Spring Framework
Spring Layers
ORM
Web
AOP
Web MVC
DAO
Context
Core
July 27, 2008
9
Spring Framework
Lingua-Franca
Service
Interface to which we program.
Implementation
Concrete class implementing the service.
Wiring
Act of creating associations between application components.
Collaborators
Services used by a service to perform business operations
Inversion of Control
AOP
July 27, 2008
10
Spring Framework
02 Introduction to IoC & AOP
July 27, 2008
11
Spring Framework
IoC Example
public class ProductServicesImpl implements ProductServices {
public class ProductServicesTest extends TestCase {
public void testGetAllProducts() {
ProductServices service = new ProductServicesImpl();
try {
List products = service.getAllProducts(“30”);
assertNotNull(products);
} catch (Exception e) {
assertTrue(false);
}
}
}
July 27, 2008
JNDI Lookup
}
ProductServiceImpl
new PricingServiceImpl()
public List getAllProducts(String loanTerm) throws Exception {
PricingServiceImpl service = new PricingServiceImpl();
return service.getAllProducts(loanTerm);
}
PricingServiceImpl
12
Spring Framework
IoC Example - revisited
public class ProductServicesImpl implements ProductServices {
public List getAllProducts(String loanTerm) throws Exception {
return service.getAllProducts(loanTerm);
}
public void setPricingService(PricingService service) {
this.service = service;
}
}
July 27, 2008
By constructor injection
public List getAllProducts(String loanTerm, PricingService service)
throws Exception {
return service.getAllProducts(loanTerm);
}
ProductServiceImpl
By setter injection
private PricingService service;
PricingServiceImpl
13
Spring Framework
Inversion of Control
It is the acquisition of dependent objects that is being inverted.
Hence, can be termed as “Dependency Injection”
Applying IoC, objects are given their dependent objects at creation
time (at runtime) by some external entity that coordinates with
each object in the system.
July 27, 2008
14
Spring Framework
Aspect Oriented Programming
Complements OOP
Decomposition of aspects/concerns
Modularization of concerns that would otherwise cut across
multiple objects
Reduces duplicate code
Usages
Logging
Persistence
Transaction Management
Debugging
Performance Metrics
July 27, 2008
15
Spring Framework
Cross Cutting Concerns
July 27, 2008
16
Spring Framework
Cross Cutting Concerns
Non-AOP representation
July 27, 2008
17
Spring Framework
Cross Cutting Concerns
AutoRate
Update Job
Generate Loan
Products
Loan
Prequalification
Reporting
Logging
Transaction Management
AOP representation
Security
July 27, 2008
18
Spring Framework
Spring @ Work
Business Objects / POJOs
Configuration Metadata
Spring
Container
produces
Configured
Ready-to-use System
July 27, 2008
19
Spring Framework
Spring Installation
Download the JAR files from,
http://www.springframework.org/download
Copy them to the dependency folder.
If you start afresh, you might need logging
Add a log4j.properties to the ROOT of class folder
Add the following to the file to direct all logging to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p %c - %m%n
log4j.rootLogger=INFO, stdout
log4j.logger.org.springframework=DEBUG (or ERROR)
Start coding
Build your own preferred way using Ant, Maven, …
July 27, 2008
20
Spring Framework
Traditional Hello World!
HelloWorldService.java
HelloWorldServiceImpl.java
package spring;
package spring;
public interface HelloWorldService {
public void sayHello();
}
public class HelloWorldImpl implements
HelloWorldService {
private String message;
private HelloWorldImpl() { }
public HelloWorldImpl(String message) {
this.message = message;
}
public void sayHello() {
System.out.println(“Hello “ + message);
}
public void setMessage(String message) {
this.message = message;
}
}
July 27, 2008
21
Spring Framework
Configuring (hello.xml)
<?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-2.0.xsd">
<bean id=“helloWorldService“ class="spring.HelloWorldImpl">
<property name=“message">
<value>Welcome to Spring!</value>
</property>
</bean>
</beans>
* DTD version for the schema is also available and can be declared as under,
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN“ "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
July 27, 2008
22
Spring Framework
The Actual Implementation – HelloWorld.java
package spring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class HelloWorld {
public static void main(String[] args) throws Exception {
ClassPathResource resource = new ClassPathResource(“hello.xml”);
BeanFactory factory = new XmlBeanFactory(resource);
HelloWorldService helloWorldService = (HelloWorldService) factory.getBean("helloWorldService");
helloWorldService.sayHello();
}
}
July 27, 2008
23
Spring Framework
IoC in an Enterprise Application
A service bean using the EJB way,
private OrderService orderService;
public void doRequest(HttpServletRequest request) {
Order order = createOrder(request);
OrderService service = getOrderService();
service.createOrder(order);
}
private OrderService getOrderService() throws CreateException {
if (orderService == null) {
Context initial = new InitialContext();
Context ctx = (Context) initial.lookup(“java:comp/env”);
Object ref = ctx.lookup(“ejb/OrderServiceHome”);
OrderServiceHome home = (OrderServiceHome) PortableRemoteObject.narrow(ref,
OrderService.class);
orderService = home.create();
}
return orderService;
}
July 27, 2008
24
Spring Framework
IoC in an Enterprise Application
Magic the dependency injection way,
private OrderService orderService;
public void doRequest(HttpServletRequest request) {
Order order = createOrder(request);
orderService.createOrder(order);
}
public void setOrderService(OrderService service) {
orderService = service;
}
July 27, 2008
25
Spring Framework
03 The Core
July 27, 2008
26
Spring Framework
Spring Beans
may be POJO/EJB/WebService
Spring’s world revolves all around Beans
Generated using two different containers,
Bean Factory
Provides basic support for dependency injection
Application Context
Built over BeanFactory to provide support for i18N, events, and file resources.
Wiring done using bean definitions
Specified as Configuration Metadata
July 27, 2008
27
Spring Framework
Bean Factory
Implementation of Factory design pattern.
Creates associations between objects, doles out fully
configured, ready to use objects.
Manages all the beans in the container.
July 27, 2008
28
Spring Framework
Instantiating Container
Using Bean Factories
In version 2.0
Resource resource = new FileSystemResource(“beans.xml”);
BeanFactory factory = new XmlBeanFactory(resource);
In version 1.0
FileInputStream stream = new FileInputStream(“beans.xml”);
BeanFactory factory = new XmlBeanFactory(stream);
July 27, 2008
29
Spring Framework
Resource Interface
In-box wrappers available for,
UrlResource
ClassPathResource
FileSystemResource
ServletContextResource
InputStreamResource
ByteArrayResource
Also, provides for loading of resources such as images, css, js
etc. in a web application.
July 27, 2008
30
Spring Framework
Resource Interface
Resource Interface,
public interface Resource extends InputStreamSource
Methods,
boolean exists()
boolean isOpen()
InputStream getInputStream()
String getDescription()
often returns fully qualified file name or the actual URL
URL getURL()
File getFile()
String getFilename()
Resource createRelative(String relativePath)
July 27, 2008
31
Spring Framework
Application Context
Aggregates information about the application that can be used by
all components.
Various implementations are,
ClassPathXmlApplicationContext
FileSystemXmlApplicationContext
XmlWebApplicationContext
Instantiating,
ApplicationContext context = new
FileSystemXmlApplicationContext(“c:\spring\beans.xml”);
July 27, 2008
32
Spring Framework
Application Context – Multiple Context’s
Loading multiple contexts
String[] ctxs = new String[] { “ctx1.xml”, “ctx2.xml” };
Loading hiererichal contexts
ApplicationContext parent = new ClassPathXmlApplicationContext (“ctx1.xml”);
ApplicationContext child = new FileSystemXmlApplicationContext(“ctx2.xml”, parent);
July 27, 2008
33
Spring Framework
Configuration Metadata
Configuration can be done using,
XML configuration files
Java property files
Programmatically using API
Annotations
Spring JavaConfig*
July 27, 2008
34
Spring Framework
Defining Bean
Bean definition contains the following attributes,
id/name
class
scope: singleton/prototype/custom
constructor arguments
properties
auto wiring mode
dependency checking mode
lazy-initialization mode
initialization method
destruction method
and much more…
July 27, 2008
35
Spring Framework
Sample Bean Definition
A basic bean definition,
<beans>
<bean id=“sampleBean" class=“spring.SampleSpringBeanClass“ scope=“singleton”
auto-wire=“byName” dependency-check=“simple” lazy-init=“true”
init-method=“myInitMethod” destroy-method=“myDestroyMethod” >
<constructor-arg value=“Hello World” />
<property name=“prop1” value=“value1” />
<property name=“prop2” ref=“anotherBean” />
</bean>
</beans>
July 27, 2008
36
Spring Framework
Defining Bean – short-circuit
The arcane way of XML,
<beans>
<bean id=“sampleBean" class=“spring.SampleSpringBeanClass“>
<property>
<name>prop1</name>
<value>value1</value>
</property>
</bean>
</beans>
Short-hand notation
<property name=“…” value=“…” />
<constructor-arg value=“…” />
<property name=“…” ref=“…” />
<entry key=“…” value=“…” />
<entry key-ref=“key reference” value=“…” />
July 27, 2008
37
Spring Framework
Separating Concerns
Importing other resources inside another resource
<beans>
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
</beans>
July 27, 2008
38
Spring Framework
Bean Aliases
In bean definition itself
Using one name in the id attribute
All other names using the “name” attribute
separated by comma, semi-colon, white space
Using the <alias> element
<alias name="fromName" alias="toName"/>
July 27, 2008
39
Spring Framework
Bean Scopes
By default, all Spring beans are singletons
Prototyped beans are useful when properties need to be set
using Spring wiring
<bean id=“example” class=“spring.MyExample” scope=“singleton” />
<bean id=“example” class =“spring.MyExample” scope=“prototype” />
<bean id=“example” class =“spring.MyExample” scope=“myScope” />
In Spring 1.0,
<bean id=“example” class=“spring.MyExample” singleton=“false” />
July 27, 2008
40
Spring Framework
Bean Scopes
Scopes available,
singleton
prototype
request
session
global session
custom scope (since Spring 2.0+)
July 27, 2008
41
Spring Framework
Constructor v/s Setter Injection
Constructor Injection
Setter Injection
<bean id=“helloWorldService“
class=“spring.HelloWorldImpl">
<constructor-arg>
<value>Hello World!</value>
</constructor-arg>
</bean>
<bean id=“helloWorldService“
class=“spring.HelloWorldImpl">
<property name=“message">
<value>Hello World!</value>
</property>
</bean>
Strong dependency contract
No superfluous setter’s
Dependent properties immutable
July 27, 2008
Prevents lengthy constructors
Several ways to construct an object
Multiple dependencies of same type
Constructors pose a problem in case of
inheritance
42
Spring Framework
Constructor Argument Resolution
Example
public class Foo(Bar bar, Car car) {
//…
}
<bean name=“Foo” class=“Foo”>
<constructor-arg><bean class=“Bar” /></constructor-arg>
<constructor-arg><bean class=“Car” /></constructor-arg>
</bean>
Example
public class Example(int years, String name) {
//…
}
<bean name=“example” class=“Example”>
<constructor-arg type=“int” value=“75000” />
<constructor-arg type=“java.lang.String” value=“Spring Enabled Message” />
</bean>
<bean name=“example” class=“Example”>
<constructor-arg index=“0” value=“75000” />
<constructor-arg index=“1” value=“Spring Enabled Message” />
</bean>
July 27, 2008
43
Spring Framework
Inner Beans
Example
<bean id=“EmailService” class=“spring.EmailServiceImpl”>
<property name=“loginService”>
<bean class=“spring.LDAPLoginService” />
</property>
</bean>
Remember
Can not reuse the inner-bean instance
Useful when we want to escape AOP proxying.
July 27, 2008
44
Spring Framework
Auto Wiring
Four types of auto-wiring
byName
Find a bean whose name is same as the name of the property being wired.
byType
Find a single bean whose type matches the type of the property being wired. If more
than one bean is found, UnsatisfiedDependencyException will be thrown.
constructor
Match one or more beans in the container with the parameters of one of the
constructors of the bean being wired.
autodetect
Autowire by constructor first, then byType.
July 27, 2008
45
Spring Framework
Auto Wiring - Examples
<bean id=“pricingService” class=“….”>
<property name=“pricingDao”>
<ref bean=“pricingDao” />
</property>
<property name=“ssnService”>
<ref bean=“ssnService>
</property>
</bean>
By Name
<bean id=“pricingService” class=“…” auto-wire=“byName” />
By Type
<bean id=“pricingService” class=“…” auto-wire=“byType” />
July 27, 2008
46
Spring Framework
Auto Wiring - Advanced
Mixing auto and explicit wiring
<bean id=“pricingService” class=“…” autowire=“byName” >
<property name=“ssnService”>
<ref bean=“newSSNService” />
</property>
</bean>
By-default wiring
<beans default-autowire=“byName” >
Can pose problems while refactoring if,
Bean cannot be found
Bean is not the one, the service actually wants
July 27, 2008
47
Spring Framework
Dependency Check
Four types of dependency checks,
none
Properties that have no value are not set.
simple
Performed for primitive types and collections, except collaborators.
object
Performed only for collaborators.
all
Performed for primitives, collections and colloborators.
July 27, 2008
48
Spring Framework
Lazy Initialization
Specifying
<bean id=“myBean” class=“…” lazy-init=“true” />
By default lazy initialization
<beans default-lazy-init=“true”>
…. // various bean definitions
</beans>
July 27, 2008
49
Spring Framework
Custom init & destroy
Example
public class Example {
public void setup() {
//init method
}
public void tearDown() {
//destruction
}
//…
}
<bean id=“example” class=“Example”
init-method=“setup” destroy-method=“tearDown” />
July 27, 2008
50
Spring Framework
Factory Beans
Using a static factory method
<bean id=“myBean” class=“spring.MyClass” factory-method=“createInstance” />
Using an instance factory method
<bean id=“myFactoryBean” class=“spring.MyFactory” />
<bean id=“myBean” factory-bean=“myFactoryBean” factory-method=“createInstance” />
July 27, 2008
51
Spring Framework
Collections – java.util.List
Wiring lists,
<bean id=“myObject” class=“spring.complexObject” >
<property name="listProperty">
<list>
<value>a list element</value>
<ref bean="otherBean"/>
<ref bean="anotherBean"/>
</list>
</property>
</bean>
July 27, 2008
52
Spring Framework
Collections – java.util.Set
Wiring sets,
<bean id=“myObject” class=“spring.complexObject” >
<property name="listProperty">
<set>
<value>a list element</value>
<ref bean="otherBean"/>
<ref bean="anotherBean"/>
</set>
</property>
</bean>
July 27, 2008
53
Spring Framework
Collections – java.util.Map
Wiring maps,
<bean id=“myObject” class=“spring.complexObject” >
<property name="mapProperty">
<map>
<entry key=“firstEntry">
<value>just some string</value>
</entry>
<entry>
<key>
<value>some key</value>
</key>
<ref bean="otherBean"/>
</entry>
</map>
</property>
</bean>
July 27, 2008
54
Spring Framework
Collections – java.util.Properties
Wiring properties,
<bean id=“myObject” class=“spring.complexObject” >
<property name=“propsProperty">
<props>
<prop key=“user”>sandeep</prop>
<prop key=“org”>Headstrong</prop>
</props>
</property>
</bean>
* The values of a map key, map value or a set key, can again be any of the following,
bean | ref | idref | list | set | map | props | value | null
July 27, 2008
55
Spring Framework
Collections – Merging
Supported in Spring 2.0+
<bean id=“parent” class=“spring.ParentBean” abstract=“true”>
<property name=“propsProperty">
<props>
<prop key=“user”>sandeep</prop>
<prop key=“org”>Headstrong</prop>
</props>
</property>
</bean>
<bean id=“child” parent=“parent” >
<property name=“propsProperty”>
<props>
<prop key=“email”>[email protected]</prop>
</props>
</property>
</bean>
July 27, 2008
56
Spring Framework
Null Values
Wiring null values
<property name=“middleName”><null /></property>
July 27, 2008
57
Spring Framework
Referencing Beans
Promotes reuse of bean instances,
<ref bean=“someBean” />
<ref local=“localBean” />
In parent-child context,
<!-- in the parent context -->
<bean id=“parentBean” class=“spring.ParentBean” />
<!-- in the child context -->
<bean id=“parentBean” class=“spring.proxy.ParentBeanProxy” > <!-- the bean name is same -->
<property name=“target”>
<ref parent=“parentBean” />
</property>
</bean>
July 27, 2008
58
Spring Framework
idref
Forces check at deployment time
<bean id=“targetBean” class=“spring.TargetBean” />
<bean id=“clientBean” class=“spring.ClientBean” >
<property name=“targetBean” value=“targetBean” />
</bean>
convert to,
<bean id=“clientBean” class=“spring.ClientBean” >
<property name=“targetBean”>
<idref bean=“targetBean” />
</property>
</bean>
July 27, 2008
59
Spring Framework
i18N & Spring
Normal Spring metadata
<bean id=“dataSource” class=“…”>
<property name=“url” value=“jdbc:hsqldb:myDatabase” />
<property name=“driverClassName” value=“org.hsqldb.jdbcDriver” />
<property name=“userName” value=“appUser” />
<property name=“password” value=“appPass” />
</bean id>
Converting to properties
<bean id=“dataSource” class=“…”>
<property name=“url” value=“${database.url}” />
<property name=“driverClassName” value=“${database.driver}” />
<property name=“userName” value=“{database.user}” />
<property name=“password” value=“${database.password}” />
</bean id>
defined in a properties file,
database.url=jdbc:hsqldb:myDatabase
database.driver=org.hsqldb.jdbcDriver
database.user=appUser
database.password=appPass
July 27, 2008
60
Spring Framework
i18N & Spring
Load the property file configurer
<bean id=“propertyConfigurer”
class=“org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”>
<property name=“locations”>
<value>jdbc.properties</value>
<value>security.properties</value>
<value>logging.properties</value>
</property>
</bean id>
July 27, 2008
61
Spring Framework
Bean Inheritance
Penetration of OOP ;)
<bean id=“abstractBean” class=“spring.AbstractBean” abstract=“true” >
<property name=“name” value=“spring” />
<property name=“version” value=“2.5” />
</bean>
Inherit properties,
<bean id=“inheritedBean” parent=“abstractBean” class=“spring.ImplementedAbstractBean />
Overriding properties,
<bean id=“inheritedBean” parent=“abstractBean” class=“spring.ImplementedAbstractBean >
<property name=“name” value=“spring framework” />
</bean>
July 27, 2008
62
Spring Framework
Special Beans
Created by implementing certain interfaces, and can be used
to
become involved in bean life-cycle
load configuration from external property files
alter Spring’s dependency injection to automatically convert String
values to desired objects
load text messages, say internationalized messages
listen to and respond to events
make beans aware of their identity inside Spring container
July 27, 2008
63
Spring Framework
Events
Events handled by ApplicationContext
ContextClosedEvent
ContextRefreshedEvent
RequestHandledEvent
To respond, beans must implement the ApplicationListener
interface
public class RefreshListener implements ApplicationListener {
public void onApplicationEvent(ApplicationEvent event) {
//…
}
}
<bean id=“refreshListener” class=“RefreshListener” />
July 27, 2008
64
Spring Framework
Raising custom Events
Define an event
public class MyEvent extends ApplicationEvent {
private String str;
public MyEvent(Object source, String anyParam) {
super(source);
this.str = anyParam;
}
public String getStr() {
return this.str;
}
}
Raise the event
ApplicationContext context = …;
String param = //anything that we need to pass to the event;
context.publishEvent(new MyEvent(this, param));
July 27, 2008
65
Spring Framework
Custom Scope
Implement the interface,
org.springframework.beans.factory.config.Scope
Object get(String name, ObjectFactory objectFactory)
Object remove(String name)
void registerDestructionCallback(String name, Runnable destructionCallback)
String getConversationId()
July 27, 2008
66
Spring Framework
Custom Scope - gluing
<bean class=“org.springframework.beans.factory.config.CustomScopeConfigurer” >
<property name=“scopes” >
<map>
<entry key=“thread”>
<bean class=“spring.scope.ThreadScope” />
</entry>
</map>
</property>
</bean>
Usage,
<bean id=“myBean” class=“spring.MyBean” scope=“thread” />
July 27, 2008
67
Spring Framework
04 AOP in Detail
July 27, 2008
68
Spring Framework
AOP lingua-franca
Aspect
Modularization of a concern/cross-cutting functionality
Join Point
Point during the execution of a program where an aspect is plugged in
Advice
Action taken at a particular Join Point
Point Cut
Set of Join Points specifying when an advice should be woven
Introduction
Adding new methods or fields to an existing class
Target
Class that is being advised
Proxy
Object created after applying advice
Weaving
Process of applying aspects to target object to create new proxy objects
Can take place at several points during a class lifetime
Compile Time: Requires special compiler.
Classload Time
RunTime
July 27, 2008
69
Spring Framework
Spring & AOP
Spring advice is written in Java*
It advises objects only at runtime
If our class implements the required interface, proxies are generated using
java.lang.reflect.Proxy class. Favored for results in more loosely coupled
application.
If it does not, it uses CGLIB to generate subclass proxies
Implements AOP Alliance interfaces
Resuable code with other compatible AOP frameworks
Supports only method joinpoints
Frameworks such as AspectJ, JBoss support field joinpoints too
July 27, 2008
70
Spring Framework
Advice
Types of advice offered by Spring
Before
Called before the target method is invoked
After (returning)
Called after the invocation of the target method which returns normally.
(After) Throws
Called when target method throws an exception
After (finally) *
Called when target method is invoked, no matter how it returns.
Around
Intercepts calls to the target method
Introduction
Used to build composite objects
July 27, 2008
71
Spring Framework
BeforeAdvice
Implement the MethodBeforeAdvice
public interface MethodBeforeAdvice {
void before(Method method, Object[] args, Object target) throws Throwable
}
public class WelcomeAdvice implements MethodBeforeAdvice {
public void before(Method method, Object[] args, Object target) throws Throwable {
Customer cust = (Customer) args[0];
System.out.println(“Hello “ + cust.getName() );
}
}
<bean id=“myTarget” class=“spring.EmailInboxImpl” />
<bean id=“welcomeAdvice” class=“spring.advice.WelcomeAdvice” />
<bean id=“inbox” class=“org.springframework.aop.framework.ProxyFactoryBean”>
<property name=“proxyInterfaces” value=“spring.EmailInbox” />
<property name=“interceptorNames”>
<list><value>welcomeAdvice</value></list>
</property>
<property name=“target” ref=“myTarget” />
</bean>
July 27, 2008
72
Spring Framework
AfterAdvice
Implement the AfterReturningAdvice
public interface AfterReturningAdvice {
void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable
}
public class ThankYouAdvice implements AfterReturningAdvice {
void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println(“Thanks.“);
}
}
<bean id=“myTarget” class=“spring.LogOutImpl” />
<bean id=“thankYouAdvice” class=“spring.advice.ThankYouAdvice” />
<bean id=“inbox” class=“org.springframework.aop.framework.ProxyFactoryBean”>
<property name=“proxyInterfaces” value=“spring.LogOut” />
<property name=“interceptorNames”>
<list><value>thankYouAdvice</value></list>
</property>
<property name=“target” ref=“myTarget” />
</bean>
July 27, 2008
73
Spring Framework
ThrowsAdvice
Implement the ThrowsAdvice interface
public interface ThrowsAdvice {
void afterThrowing(Throwable throwable);
void afterThrowing(Method method, Object[] args, Object target, Throwable throwable);
}
* Must implement atleast one method of the two signatures
July 27, 2008
74
Spring Framework
AroundAdvice
Implement the MethodInterceptor interface
Controls whether the actual target method is actually invoked
Gives control over the return value
public interface MethodInterceptor {
public Object invoke(MethodInvocation invocation);
}
public class MyInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) {
//do something before the method invocation
Object returnValue = invocation.proceed();
//do something after the method invocation
return someReturnValue;
}
}
July 27, 2008
75
Spring Framework
Introductions
Implement the IntroductionInterceptor interface
build composite objects, adding new methods/attributes to the advised class
public class AuditableMixin implements IntroductionInterceptor, Auditable {
public boolean implementsInterface(Class intf) {
return intf.isAssignableFrom(Auditable.class);
}
public Object invoke(MethodInvocation m) throws Throwable {
if (implementsInterface(m.getMethod().getDeclaringClass())) {
return m.getMethod().invoke(this, m.getArguments());
} else {
return m.proceed();
}
}
private Date lastModifiedDate;
public Date getLastModifiedDate() { .. }
public void setLastModifiedDate(Date lastModifiedDate) { … }
}
July 27, 2008
76
Spring Framework
PointCut
Implement the PointCut interface
public interface Pointcut {
ClassFilter getClassFilter();
MethodMatcher getMethodMatcher();
}
public interface ClassFilter {
boolean matches(Class clazz);
}
public interface MethodMatcher {
boolean matches(Method m, Class targetClass);
boolean matches(Method m, Class targetClass, Object[] args);
boolean isRuntime();
}
July 27, 2008
77
Spring Framework
PointCut Implementation
NameMatchMethodPointcut
<bean id=“orderMethodPointcut“
class="org.springframework.aop.support.NameMatchMethodPointcut">
<property name="mappedName“ value=“order*” />
</bean>
RegexpMethodPointCut: Matches a Perl5 regex to a fully qualified method name
<bean id=“beanMethodsPointcut“ class="org.springframework.aop.support.RegexpMethodPointcut">
<property name=“patterns“>
<list>
<value>.*\.get.*</value>
<value>.*\.set.*</value>
</list>
</property>
</bean>
July 27, 2008
78
Spring Framework
Spring Advisors
Aspect’s as a combination of an Advice and a Pointcut.
Each built in Advice has an Advisor
Example
<bean id="debugInterceptor" class="DebugInterceptor"/>
<bean id=“debugAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<constructor-arg ref="debugInterceptor"/>
<property name="pattern“ value=“.*\.get.*” />
</bean>
<bean id=“myTarget” class=“spring.MyServiceImpl” />
<bean id=“myService” class=“org.springframework.aop.framework.ProxyFactoryBean”>
<property name=“proxyInterfaces” value=“spring.MyService” />
<property name=“interceptorName” value=“debugAdvisor” />
<property name=“target” value=“myTarget” />
</bean>
July 27, 2008
79
Spring Framework
Auto Proxy
Enables Spring container to generate proxies for us
Implemented using,
BeanNameAutoProxyCreator: Apply aspect uniformly over a set of beans
DefaultAdvisorAutoProxyCreator: Apply advisors uniformly over a set of beans
July 27, 2008
80
Spring Framework
Auto Proxy Examples
BeanNameAutoProxyCreator
<bean id=“performanceProxyCreator”
class=“org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator” >
<property name=“beanNames”>
<list>
<value>*Service<value>
<value>*DAO<value>
<list>
</property>
<property name=“interceptorNames” value=“myPerformanceInterceptor” />
</bean>
July 27, 2008
81
Spring Framework
Auto Proxy Examples
DefaultAdvisorAutoProxyCreator
<bean id=“advisor” class=“org.springframework.aop.support.RegexpMethodPointcutAdvisor”>
<property name=“advice” ref=“myPerformanceInterceptor”>
<property name=“pattern” value=“.+Service\..+” />
<bean>
<bean id=“performanceProxyCreator”
class=“org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator” >
<property name=“interceptorNames” value=“myPerformanceInterceptor” />
</bean>
July 27, 2008
82
Spring Framework
05 Bean Lifecycle
July 27, 2008
83
Spring Framework
In Bean Factory Container
July 27, 2008
84
Spring Framework
In Application Context
July 27, 2008
85
Spring Framework
Graceful Shutdown
Not applicable for web applications – hooks are already in
place for Spring’s web-based ApplicationContext
public static void main(String[] args) {
AbstractApplicationContext ctx = new …
// add a shutdown hook
ctx.registerShutdownHook();
}
July 27, 2008
86
Spring Framework
Knowing Who You Are
Self Aware Beans – that handle the Spring container
themselves, and may control the container’s behavior
Three ways to make beans aware,
BeanNameAware
BeanFactoryAware
ApplicationContextAware
July 27, 2008
87
Spring Framework
Creating Self Aware Beans
BeanNameAware
public interface BeanNameAware {
void setBeanName(String name);
}
BeanFactoryAware
public interface BeanFactoryAware {
void setBeanFactory(BeanFactory factory);
}
ApplicationContextAware
public interface ApplicationContextAware {
void setApplicationContext(ApplicationContext context);
}
July 27, 2008
88
Spring Framework
06 Extensibility
July 27, 2008
89
Spring Framework
Extensibility?
Mechanism for schema-based extensions to the base Spring
XML format for definining and configuring beans
Authoring an XML Schema
Coding a custom NamespaceHandler implementation
Coding one or more BeanDefinitionParser implementations
Gluing the above into Spring
July 27, 2008
90
Spring Framework
Extensibility Example
Element <myns:dateFormat /> for SimpleDateFormat objects.
<myns:dateFormat id=“myDate” pattern=“yyyy-MM-dd HH:mm” lenient=“true” />
analogous to,
<bean id=“dateFormat” class=“java.text.SimpleDateFormat”>
<constructor-arg value=“yyyy-MM-dd HH:mm” />
<property name=“lenient” value=“true” />
</bean>
July 27, 2008
91
Spring Framework
Authoring Schema
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns="http://www.springframework.org/schema/myns"
xmlns:xsd="http://www.w3.org/2001/XMLSchema“
xmlns:beans="http://www.springframework.org/schema/beans"
targetNamespace="http://www.mycompany.com/schema/myns"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xsd:import namespace="http://www.springframework.org/schema/beans"/>
<xsd:element name="dateformat">
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="beans:identifiedType">
<xsd:attribute name="lenient" type="xsd:boolean"/>
<xsd:attribute name="pattern" type="xsd:string" use="required"/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
</xsd:schema>
July 27, 2008
92
Spring Framework
Namespace Handler
Helps parse all elements in the new namespace
NamespaceHandler
init()
called before the handler is used
BeanDefinition parse(Element, ParserContext)
called when Spring encounters a top-level element
BeanDefinitionHolder decorate(Node, BeanDefinitionHolder,
ParserContext)
called when Spring encounters an attribute or nested element of a different namespace
July 27, 2008
93
Spring Framework
NamespaceHandler
NamespaceHandlerSupport
package spring.xml;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
public class MyNamespaceHandler extends NamespaceHandlerSupport {
public void init() {
registerBeanDefinitionParser("dateformat", new SimpleDateFormatBeanDefinitionParser());
}
}
July 27, 2008
94
Spring Framework
Bean Definition Parser
public class SimpleDateFormatBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
protected Class getBeanClass(Element element) {
return SimpleDateFormat.class;
}
protected void doParse(Element element, BeanDefinitionBuilder bean) {
// this will never be null since the schema explicitly requires that a value be supplied
String pattern = element.getAttribute("pattern");
bean.addConstructorArg(pattern);
// this however is an optional property
String lenient = element.getAttribute("lenient");
if (StringUtils.hasText(lenient)) {
bean.addPropertyValue("lenient", Boolean.valueOf(lenient));
}
}
}
July 27, 2008
95
Spring Framework
Register Handler/Parser
Place the following property files in the META-INF directory in root
spring.handlers
mapping of XML schema URI to namespace handler classes
http\://www.mycompany.com/schema/myns
=org.springframework.samples.xml.MyNamespaceHandler
spring.schemas
mapping of XML schema location to classpath resources
http\://www.mycompany.com/schema/myns/myns.xsd
=org/springframework/samples/xml/myns.xsd
July 27, 2008
96
Spring Framework
Usage
<beans>
<!-- as a top-level bean -->
<myns:dateformat id="defaultDateFormat" pattern="yyyy-MM-dd HH:mm" lenient="true"/>
<bean id=“someBean" class=“spring.SomeBean” >
<property name="dateFormat">
<!-- as an inner bean -->
<myns:dateformat pattern="HH:mm MM-dd-yyyy"/>
</property>
</bean>
</beans>
July 27, 2008
97
Spring
The Beginning…
July 27, 2008
98
Spring Universe
SpringSource Application Platform
Applications
Eclipse Equinox
(OSGi)
Spring Dynamic Kernel Mode
• Real time server Updates
• Side-by-side Resource Versioning
• Run old & new applications
• Smaller server footpriint
• Inject Bundles at runtime
JARs
Tomcat
Spring Personalities
Logging Subsystem
Tracing Subsystem
Exception Detection/Reporting
Enterprise Bundle Repository
July 27, 2008
99
Spring Universe
Other Spring Projects
Spring WebFlow
Provides infrastructure for building and running RIA, builds over Spring MVC
Spring Web Services
Helps create document-driven Webservices, facilitates contract-first SOAP service deployment.
Spring Security (aka Acegi)
Security Solution for web applications – supports JSR 250 (EJB3), ACL, SiteMinder, CAS3, Portlets,
Webflow, OpenID, Windows NTLM and more.
Spring Dynamic Modules for OSGi Services Platform
Helps build Spring applications that can run in an OSGi platform with better separation of modules.
Spring Batch
Framework for development of robust batch applications using POJOs.
July 27, 2008
100
Spring Universe
Other Spring Projects
Spring Integration
An extension of Spring model to support Enterprise Integration Patterns.
Spring LDAP
Library for Java based LDAP operations based on Spring’s Template pattern.
Spring IDE
GUI for working with Spring configuration files over Eclipse.
Spring Modules
A collection of modules, add-ons and integration tools for Spring, like Ant, Flux, HiveMind, Lucene, O/R
Broker, OSWorkflow, Tapestry, EHCache, OSCache, GigaSpaces, db4o, Drools, Jess, Groovy, Velocity,
Jackrabbit, Jeceira and many many more…
Spring Java Config
Provides pure-Java, type-safe option for configuring Spring Contexts.
July 27, 2008
101
Spring Universe
Other Spring Projects
Spring BeanDoc
Tool for documenting and graphing Spring bean factories and context files.
Spring RCP
Platform to construct rich Swing applications. Analogous to Eclipse RCP.
Grid Gain*
A grid-computing platform in Java which is a natural extension of development methodologies including
annotations, Spring dependency injection, and AOP-based grid-enabling.
July 27, 2008
102
Other Framework’s
Dependency Injection
Avalon
Supports Service Locator & Interface Injection, but is intrusive.
Google Guice
All configuration is in Java, reduces a lot of boiler plate, and can be up to 50x faster than Spring.
HiveMind
Is more of a component based registry provider.
PicoContainer & NanoContainer
Very lightweight (~50kb) but supports only Singletons.
EJB 3 (such as JBoss Seam)
Is a standard and comes as a whole package.
Naked Objects
May be used in conjunction.
July 27, 2008
103
Other Framework’s
AOP
AspectJ
Compile team weaving, supports field joinpoints. Spring 2.0+ complements AspectJ. Aspects not in Java
JBoss AOP
Comes with pre-packaged aspects such as caching, asynchronous communication, security, remoting…
AspectWerkz
Similar to AspectJ with Aspects written in Java.
Object Teams
A new entrant to AOP world, visits the concepts of Teams/Modules on a set of role objects.
Dynaop
Quite old, doesn’t offers much, but, is damn fast (up to 5x faster than Spring)
For better comparison, visit http://www.ibm.com/developerworks/library/j-aopwork1/
July 27, 2008
104
Spring Framework
References & Feedback
July 27, 2008
105
Spring Framework
References
Websites
http://www.springframework.org
http://martinfowler.com/articles/injection.html
http://docs.codehaus.org/display/PICO/Inversion+of+Control
http://static.springframework.org/spring/docs/2.5.5/reference/index.html
http://www.theserverside.com/articles/article.tss?l=SpringFramework
http://www.ibm.com/developerworks/library/j-aopwork1/
Books
Spring In Action by Craig Walls and Ryan Breidenbach
Spring j2ee Application Framework by Spring Development Team
J2EE Without EJB by Rod Johnson and Juergen Holler
Spring Live by Matt Raible
July 27, 2008
106
Spring Framework
Questions/Feedback
For any queries or suggestions,
Post it on,
http://azcarya.googlecode.com
Drop me a mail at,
[email protected]
July 27, 2008
107
Hope this helps.
SANDEEP GUPTA
© 2008, under Creative Commons 3.0 Attribution License
July 27, 2008
108