SPRING FRAMEWORK Basics of 1July 27, 2008. Spring Framework Basics Introduction to IoC and AOP...
-
Upload
koby-coomer -
Category
Documents
-
view
214 -
download
0
Transcript of SPRING FRAMEWORK Basics of 1July 27, 2008. Spring Framework Basics Introduction to IoC and AOP...
SPRING FRAMEWORKBasics of
1July 27, 2008
Spring Framework
BasicsIntroduction to IoC and AOPSpring CoreAOP in DetailBean LifecycleExtensibilitySpring - The Beginning…
ReferencesQuestions/Feedback
Agenda
2July 27, 2008
Spring Framework
01 Basics
3July 27, 2008
Spring Framework
Spring is a Lightweight, Inversion of Control and Aspect-Oriented Container FrameworkLightweightInversion of ControlAspect OrientedContainerFramework
Spring?
4July 27, 2008
Spring Framework
Play role in Enterprise Application ArchitectureCore SupportWeb Application Development SupportEnterprise Application Development Support
Spring Triangle
Spring Goals
55July 27, 2008
Spring Framework
Spring Triangle
6
Depe
nden
cy In
jecti
on
Aspect Oriented Programm
ing
Enterprise Service Abstractions
6July 27, 2008
Spring Framework
To make J2EE easier to use and promote EBPAlways better to program to interfaces than classesJavaBeans are a great way to configure applicationsFramework should not force to catch exceptions if one is unlikely to recover from themTesting is essential and framework should make it easierTo make integration with existing technologies easierTo easily integrate in existing projects
Spring Objectives
7July 27, 2008
Spring Framework
Organizes middle tier objectsEliminates proliferation of singletonsSpring is mostly non-intrusive*Applications built on Spring are easy to Unit TestUse of EJB becomes an implementation choiceConsistent framework for Data Access whether JDBC or O/R mappingAny part of Spring can be used in isolation.Provides for flexible architectureBenefit to all application layers
Spring Advantages
8July 27, 2008
Spring Framework
Spring Layers
9
Core
AOP Web MVC
ORM Web
DAO Context
July 27, 2008
Spring Framework
ServiceInterface to which we program.
ImplementationConcrete class implementing the service.
WiringAct of creating associations between application components.
Collaborators Services used by a service to perform business operations
Inversion of ControlAOP
Lingua-Franca
10July 27, 2008
Spring Framework
02 Introduction to IoC & AOP
11July 27, 2008
Spring Framework
public class ProductServicesImpl implements ProductServices {
public List getAllProducts(String loanTerm) throws Exception {PricingServiceImpl service = new PricingServiceImpl();return service.getAllProducts(loanTerm);
}}
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);}
}}
IoC Example
12
ProductServiceImpl
PricingServiceImpl
new
Pric
ingS
ervi
ceIm
pl()
JND
I Loo
kup
July 27, 2008
Spring Framework
public class ProductServicesImpl implements ProductServices {
private PricingService service;
public List getAllProducts(String loanTerm, PricingService service) throws Exception {return service.getAllProducts(loanTerm);
}
public List getAllProducts(String loanTerm) throws Exception {return service.getAllProducts(loanTerm);
}
public void setPricingService(PricingService service) {this.service = service;
}}
IoC Example - revisited
13
ProductServiceImpl
PricingServiceImpl
By s
etter
inje
ction
By c
onst
ruct
or in
jecti
on
July 27, 2008
Spring Framework
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.
Inversion of Control
14July 27, 2008
Spring Framework
Complements OOPDecomposition of aspects/concernsModularization of concerns that would otherwise cut across multiple objectsReduces duplicate codeUsages
LoggingPersistenceTransaction ManagementDebuggingPerformance Metrics
Aspect Oriented Programming
15July 27, 2008
Spring Framework
Cross Cutting Concerns
16
Auto Rate Update Job
Generate Loan Products
Loan Prequalification
Reporting Tra
nsac
tion
Man
agem
ent
Sec
urit
y
Log
ging
/Exc
epti
on H
andl
ing
Per
form
ance
Met
rics
July 27, 2008
Spring Framework
Non-AOP representation
Cross Cutting Concerns
17
Auto Rate Update Job
Generate Loan Products
Loan Prequalification
Reporting
Transaction Management
Security
Logging
Performance Metrics
July 27, 2008
AOP representation
Logg
ing
Tran
sacti
on M
anag
emen
t
Security
Spring Framework
Cross Cutting Concerns
18
AutoRate Update Job
Generate Loan Products
Loan Prequalification Reporting
July 27, 2008
Spring Framework
Spring @ Work
19
ConfiguredReady-to-use System
SpringContainerConfiguration Metadata
Business Objects / POJOs
produces
July 27, 2008
Spring Framework
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 folderAdd the following to the file to direct all logging to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d %p %c - %m%nlog4j.rootLogger=INFO, stdoutlog4j.logger.org.springframework=DEBUG (or ERROR)
Start codingBuild your own preferred way using Ant, Maven, …
Spring Installation
20July 27, 2008
Spring Framework
HelloWorldService.javapackage spring;
public interface HelloWorldService {public void sayHello();
}
HelloWorldServiceImpl.javapackage spring;
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;
}}
21
Traditional Hello World!
July 27, 2008
Spring Framework
<?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">
Configuring (hello.xml)
22July 27, 2008
Spring Framework
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();
}}
The Actual Implementation – HelloWorld.java
23July 27, 2008
Spring Framework
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;
}
IoC in an Enterprise Application
24July 27, 2008
Spring Framework
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;
}
IoC in an Enterprise Application
25July 27, 2008
Spring Framework
03 The Core
26July 27, 2008
Spring Framework
may be POJO/EJB/WebServiceSpring’s world revolves all around BeansGenerated using two different containers,
Bean FactoryProvides basic support for dependency injection
Application ContextBuilt over BeanFactory to provide support for i18N, events, and file resources.
Wiring done using bean definitionsSpecified as Configuration Metadata
Spring Beans
27July 27, 2008
Spring Framework
Implementation of Factory design pattern.Creates associations between objects, doles out fully configured, ready to use objects.Manages all the beans in the container.
Bean Factory
2828July 27, 2008
Spring Framework
Using Bean FactoriesIn version 2.0
Resource resource = new FileSystemResource(“beans.xml”);BeanFactory factory = new XmlBeanFactory(resource);
In version 1.0FileInputStream stream = new FileInputStream(“beans.xml”);BeanFactory factory = new XmlBeanFactory(stream);
Instantiating Container
2929July 27, 2008
Spring Framework
In-box wrappers available for,UrlResourceClassPathResourceFileSystemResourceServletContextResourceInputStreamResourceByteArrayResource
Also, provides for loading of resources such as images, css, js etc. in a web application.
Resource Interface
3030July 27, 2008
Spring Framework
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)
Resource Interface
3131July 27, 2008
Spring Framework
Aggregates information about the application that can be used by all components.
Various implementations are,ClassPathXmlApplicationContextFileSystemXmlApplicationContextXmlWebApplicationContext
Instantiating,ApplicationContext context = new FileSystemXmlApplicationContext(“c:\spring\
beans.xml”);
Application Context
3232July 27, 2008
Spring Framework
Loading multiple contextsString[] ctxs = new String[] { “ctx1.xml”, “ctx2.xml” };
Loading hiererichal contextsApplicationContext parent = new ClassPathXmlApplicationContext (“ctx1.xml”);ApplicationContext child = new FileSystemXmlApplicationContext(“ctx2.xml”, parent);
Application Context – Multiple Context’s
3333July 27, 2008
Spring Framework
Configuration can be done using,XML configuration filesJava property filesProgrammatically using APIAnnotationsSpring JavaConfig*
Configuration Metadata
3434July 27, 2008
Spring Framework
Bean definition contains the following attributes,id/nameclassscope: singleton/prototype/customconstructor argumentspropertiesauto wiring modedependency checking modelazy-initialization modeinitialization methoddestruction methodand much more…
Defining Bean
35July 27, 2008
Spring Framework
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>
Sample Bean Definition
3636July 27, 2008
Spring Framework
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=“…” />
Defining Bean – short-circuit
3737July 27, 2008
Spring Framework
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>
Separating Concerns
38July 27, 2008
Spring Framework
In bean definition itselfUsing one name in the id attributeAll other names using the “name” attribute
separated by comma, semi-colon, white space
Using the <alias> element<alias name="fromName" alias="toName"/>
Bean Aliases
39July 27, 2008
Spring Framework
By default, all Spring beans are singletonsPrototyped 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” />
Bean Scopes
4040July 27, 2008
Spring Framework
Scopes available,singletonprototyperequestsessionglobal sessioncustom scope (since Spring 2.0+)
Bean Scopes
4141July 27, 2008
Spring Framework
Constructor Injection
<bean id=“helloWorldService“ class=“spring.HelloWorldImpl"><constructor-arg>
<value>Hello World!</value></constructor-arg>
</bean>
Strong dependency contractNo superfluous setter’sDependent properties immutable
Setter Injection
<bean id=“helloWorldService“ class=“spring.HelloWorldImpl"><property name=“message">
<value>Hello World!</value></property>
</bean>
Prevents lengthy constructorsSeveral ways to construct an objectMultiple dependencies of same typeConstructors pose a problem in case of inheritance
42
Constructor v/s Setter Injection
July 27, 2008
Spring Framework
Examplepublic 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>
Examplepublic 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>
Constructor Argument Resolution
43July 27, 2008
Spring Framework
Example<bean id=“EmailService” class=“spring.EmailServiceImpl”>
<property name=“loginService”><bean class=“spring.LDAPLoginService” />
</property></bean>
RememberCan not reuse the inner-bean instanceUseful when we want to escape AOP proxying.
Inner Beans
44July 27, 2008
Spring Framework
Four types of auto-wiringbyNameFind a bean whose name is same as the name of the property being wired.
byTypeFind a single bean whose type matches the type of the property being wired. If more than one bean is found, UnsatisfiedDependencyException will be thrown.
constructorMatch one or more beans in the container with the parameters of one of the constructors of the bean being wired.
autodetectAutowire by constructor first, then byType.
Auto Wiring
4545July 27, 2008
Spring Framework
<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” />
Auto Wiring - Examples
4646July 27, 2008
Spring Framework
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 foundBean is not the one, the service actually wants
Auto Wiring - Advanced
4747July 27, 2008
Spring Framework
Four types of dependency checks,noneProperties that have no value are not set.
simplePerformed for primitive types and collections, except collaborators.
objectPerformed only for collaborators.
allPerformed for primitives, collections and colloborators.
Dependency Check
4848July 27, 2008
Spring Framework
Specifying<bean id=“myBean” class=“…” lazy-init=“true” />
By default lazy initialization<beans default-lazy-init=“true”>
…. // various bean definitions</beans>
Lazy Initialization
4949July 27, 2008
Spring Framework
Example
public class Example {public void setup() {
//init method}public void tearDown() {
//destruction}//…
}
<bean id=“example” class=“Example” init-method=“setup” destroy-method=“tearDown” />
Custom init & destroy
50July 27, 2008
Spring Framework
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” />
Factory Beans
51July 27, 2008
Spring Framework
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>
Collections – java.util.List
52July 27, 2008
Spring Framework
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>
Collections – java.util.Set
5353July 27, 2008
Spring Framework
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>
Collections – java.util.Map
5454July 27, 2008
Spring Framework
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
Collections – java.util.Properties
5555July 27, 2008
Spring Framework
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>
Collections – Merging
5656July 27, 2008
Spring Framework
Wiring null values<property name=“middleName”><null /></property>
Null Values
57July 27, 2008
Spring Framework
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>
Referencing Beans
5858July 27, 2008
Spring Framework
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>
idref
5959July 27, 2008
Spring Framework
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:myDatabasedatabase.driver=org.hsqldb.jdbcDriverdatabase.user=appUserdatabase.password=appPass
i18N & Spring
60July 27, 2008
Spring Framework
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>
i18N & Spring
61July 27, 2008
Spring Framework
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>
Bean Inheritance
6262July 27, 2008
Spring Framework
Created by implementing certain interfaces, and can be used to
become involved in bean life-cycleload configuration from external property filesalter Spring’s dependency injection to automatically convert String values to desired objectsload text messages, say internationalized messageslisten to and respond to eventsmake beans aware of their identity inside Spring container
Special Beans
63July 27, 2008
Spring Framework
Events handled by ApplicationContextContextClosedEventContextRefreshedEventRequestHandledEvent
To respond, beans must implement the ApplicationListener interfacepublic class RefreshListener implements ApplicationListener {
public void onApplicationEvent(ApplicationEvent event) {//…
}}
<bean id=“refreshListener” class=“RefreshListener” />
Events
64July 27, 2008
Spring Framework
Define an eventpublic 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 eventApplicationContext context = …;String param = //anything that we need to pass to the event;context.publishEvent(new MyEvent(this, param));
Raising custom Events
65July 27, 2008
Spring Framework
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()
Custom Scope
6666July 27, 2008
Spring Framework
<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” />
Custom Scope - gluing
6767July 27, 2008
Spring Framework
04 AOP in Detail
68July 27, 2008
Spring Framework
AspectModularization of a concern/cross-cutting functionality
Join PointPoint during the execution of a program where an aspect is plugged in
AdviceAction taken at a particular Join Point
Point CutSet of Join Points specifying when an advice should be woven
IntroductionAdding new methods or fields to an existing class
TargetClass that is being advised
ProxyObject created after applying advice
WeavingProcess of applying aspects to target object to create new proxy objectsCan take place at several points during a class lifetime
Compile Time: Requires special compiler.Classload TimeRunTime
AOP lingua-franca
69July 27, 2008
Spring Framework
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 interfacesResuable code with other compatible AOP frameworks
Supports only method joinpointsFrameworks such as AspectJ, JBoss support field joinpoints too
Spring & AOP
70July 27, 2008
Spring Framework
Types of advice offered by SpringBeforeCalled before the target method is invoked
After (returning)Called after the invocation of the target method which returns normally.
(After) ThrowsCalled when target method throws an exception
After (finally) *Called when target method is invoked, no matter how it returns.
AroundIntercepts calls to the target method
IntroductionUsed to build composite objects
Advice
71July 27, 2008
Spring Framework
Implement the MethodBeforeAdvicepublic 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>
BeforeAdvice
72July 27, 2008
Spring Framework
Implement the AfterReturningAdvicepublic 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>
AfterAdvice
73July 27, 2008
Spring Framework
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
ThrowsAdvice
74July 27, 2008
Spring Framework
Implement the MethodInterceptor interface
Controls whether the actual target method is actually invokedGives 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 invocationObject returnValue = invocation.proceed();//do something after the method invocation
return someReturnValue;}
}
AroundAdvice
75July 27, 2008
Spring Framework
Implement the IntroductionInterceptor interface
build composite objects, adding new methods/attributes to the advised classpublic 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) { … }
}
Introductions
76July 27, 2008
Spring Framework
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();
}
PointCut
77July 27, 2008
Spring Framework
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>
PointCut Implementation
78July 27, 2008
Spring Framework
Aspect’s as a combination of an Advice and a Pointcut.Each built in Advice has an AdvisorExample<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>
Spring Advisors
79July 27, 2008
Spring Framework
Enables Spring container to generate proxies for usImplemented using,
BeanNameAutoProxyCreator: Apply aspect uniformly over a set of beans
DefaultAdvisorAutoProxyCreator: Apply advisors uniformly over a set of beans
Auto Proxy
80July 27, 2008
Spring Framework
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>
Auto Proxy Examples
81July 27, 2008
Spring Framework
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>
Auto Proxy Examples
82July 27, 2008
Spring Framework
05 Bean Lifecycle
83July 27, 2008
Spring Framework
In Bean Factory Container
84
Instantiate
Populate Properties
BeanNameAware’ssetBeanName()
BeanFactoryAware’ssetBeanFactory()
Pre-initializationBeanPostProcessors
InitializingBean’safterPropertiesSet()
Call custom init-method
Post-initializationBeanPostProcessors
Disposable Bean’s destroy()
Call custom destroy-method
Bean is ready to use
Container is shutdown
July 27, 2008
Spring Framework
In Application Context
85
Instantiate
Populate Properties
BeanNameAware’ssetBeanName()
BeanFactoryAware’ssetBeanFactory()
Pre-initializationBeanPostProcessors
InitializingBean’safterPropertiesSet()
Call custom init-method
Post-initializationBeanPostProcessors
Disposable Bean’s destroy()
Call custom destroy-method
Bean is ready to use
Container is shutdown
ApplicationContextAware’ssetApplicationContxet()
July 27, 2008
Spring Framework
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 hookctx.registerShutdownHook();
}
Graceful Shutdown
8686July 27, 2008
Spring Framework
Self Aware Beans – that handle the Spring container themselves, and may control the container’s behavior
Three ways to make beans aware,BeanNameAwareBeanFactoryAwareApplicationContextAware
Knowing Who You Are
8787July 27, 2008
Spring Framework
BeanNameAwarepublic interface BeanNameAware {
void setBeanName(String name);}
BeanFactoryAwarepublic interface BeanFactoryAware {
void setBeanFactory(BeanFactory factory);}
ApplicationContextAwarepublic interface ApplicationContextAware {
void setApplicationContext(ApplicationContext context);}
Creating Self Aware Beans
8888July 27, 2008
Spring Framework
06 Extensibility
8989July 27, 2008
Spring Framework
Mechanism for schema-based extensions to the base Spring XML format for definining and configuring beans
Authoring an XML SchemaCoding a custom NamespaceHandler implementationCoding one or more BeanDefinitionParser implementationsGluing the above into Spring
Extensibility?
9090July 27, 2008
Spring Framework
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>
Extensibility Example
9191July 27, 2008
Spring Framework
<?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>
Authoring Schema
9292July 27, 2008
Spring Framework
Helps parse all elements in the new namespaceNamespaceHandler
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
Namespace Handler
9393July 27, 2008
Spring Framework
NamespaceHandlerSupport
package spring.xml;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
public class MyNamespaceHandler extends NamespaceHandlerSupport { public void init() { registerBeanDefinitionParser("dateformat", new SimpleDateFormatBeanDefinitionParser()); }}
NamespaceHandler
9494July 27, 2008
Spring Framework
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)); } }}
Bean Definition Parser
9595July 27, 2008
Spring Framework
Place the following property files in the META-INF directory in root
spring.handlersmapping of XML schema URI to namespace handler classes
http\://www.mycompany.com/schema/myns=org.springframework.samples.xml.MyNamespaceHandler
spring.schemasmapping of XML schema location to classpath resources
http\://www.mycompany.com/schema/myns/myns.xsd=org/springframework/samples/xml/myns.xsd
Register Handler/Parser
9696July 27, 2008
Spring Framework
<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>
Usage
9797July 27, 2008
Spring
The Beginning…
9898July 27, 2008
Spring Universe
SpringSource Application Platform
99
Enterprise Bundle Repository
Spring Dynamic Kernel Mode
• Real time server Updates• Side-by-side Resource Versioning• Run old & new applications• Smaller server footpriint• Inject Bundles at runtime
Applications
JARs
Tomcat
Spring Personalities
Eclip
se E
quin
ox(O
SGi)
Logging Subsystem Tracing Subsystem Exception Detection/Reporting
99July 27, 2008
Spring Universe
Spring WebFlowProvides infrastructure for building and running RIA, builds over Spring MVC
Spring Web ServicesHelps 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 PlatformHelps build Spring applications that can run in an OSGi platform with better separation of modules.
Spring BatchFramework for development of robust batch applications using POJOs.
Other Spring Projects
100100July 27, 2008
Spring Universe
Spring IntegrationAn extension of Spring model to support Enterprise Integration Patterns.
Spring LDAPLibrary for Java based LDAP operations based on Spring’s Template pattern.
Spring IDEGUI for working with Spring configuration files over Eclipse.
Spring ModulesA 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 ConfigProvides pure-Java, type-safe option for configuring Spring Contexts.
Other Spring Projects
101101July 27, 2008
Spring Universe
Spring BeanDocTool for documenting and graphing Spring bean factories and context files.
Spring RCPPlatform 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.
Other Spring Projects
102102July 27, 2008
Other Framework’s
AvalonSupports Service Locator & Interface Injection, but is intrusive.
Google GuiceAll configuration is in Java, reduces a lot of boiler plate, and can be up to 50x faster than Spring.
HiveMindIs more of a component based registry provider.
PicoContainer & NanoContainerVery lightweight (~50kb) but supports only Singletons.
EJB 3 (such as JBoss Seam)Is a standard and comes as a whole package.
Naked ObjectsMay be used in conjunction.
Dependency Injection
103103July 27, 2008
Other Framework’s
AspectJCompile team weaving, supports field joinpoints. Spring 2.0+ complements AspectJ. Aspects not in Java
JBoss AOPComes with pre-packaged aspects such as caching, asynchronous communication, security, remoting…
AspectWerkzSimilar to AspectJ with Aspects written in Java.
Object TeamsA new entrant to AOP world, visits the concepts of Teams/Modules on a set of role objects.
DynaopQuite 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/
AOP
104104July 27, 2008
Spring Framework
References & Feedback
105July 27, 2008
Spring Framework
Websiteshttp://www.springframework.orghttp://martinfowler.com/articles/injection.htmlhttp://docs.codehaus.org/display/PICO/Inversion+of+Controlhttp://static.springframework.org/spring/docs/2.5.5/reference/index.htmlhttp://www.theserverside.com/articles/article.tss?l=SpringFrameworkhttp://www.ibm.com/developerworks/library/j-aopwork1/
BooksSpring In Action by Craig Walls and Ryan Breidenbach Spring j2ee Application Framework by Spring Development TeamJ2EE Without EJB by Rod Johnson and Juergen HollerSpring Live by Matt Raible
References
106July 27, 2008
Spring Framework
For any queries or suggestions, Post it on,
http://azcarya.googlecode.com
Drop me a mail at,[email protected]
Questions/Feedback
107July 27, 2008
SANDEEP GUPTAHope this helps.
108July 27, 2008
© 2008, under Creative Commons 3.0 Attribution License