Introduction to Spring

jetmorebrisketΛογισμικό & κατασκευή λογ/κού

15 Αυγ 2012 (πριν από 5 χρόνια και 1 μέρα)

750 εμφανίσεις









Introduction to Spring

-
Sugi Murmu,

Technical Architect,

eternalYfe









Agenda


Architecture


JavaBeans & POJOs


XML, DTD & XSD


Spring


IDE: Netbeans or Eclipse


Tomcat


JSPs + Servlets


Spring MVC


Hibernate


Testing


Unit testing using JUnit and Selenium





Model















Architecture Overview

Presentation Tier

Business Tier

Persistence Tier

Controller 1

Controller 2

Views

BO1

(Business Object)

BO2

BO3

DAO1

(Data
Access
Object)

DAO2


Hibernate

Spring





JavaBeans

A JavaBean is a Java Object that is:



Serializable:


Ability to marshal i.e. convert the object into a format that can be stored (for example, in
a file, or transmitted across a network) and




Ability to unmarshal i.e. "re
-
construct" later in the same or another computer
environment.



Serialized format: String, XML, Byte Stream etc.



Has a null constructor : The class must have a public default constructor (no
-
argument)


Allows access to properties using getter and setter methods

Serialized format

Serialized format





JavaBeans (Contd…)

package com.eternalyfe.edu.beans;

import java.io.Serializable;

public class User implements Serializable {


private String name;


/**


* @return the name


*/


public String getName() {


return name;


}


/**


* @param name the name to set


*/


public void setName(String name) {


this.name = name;


}

}

Note

:
-


1.
If you don't define a constructor for a class, a
default parameter
-
less constructor

is automatically created by the compiler.

2.
Default constructor is created only if there are no constructors
. If you define
any

constructor for your class, no default
constructor is automatically created.





POJO

P
lain
O
ld
J
ava
O
bject

-
The term was coined by Martin Fowler, Rebecca Parsons and Josh
MacKenzie in September 2000



Just an
ordinary

Java Object, not a special object, and in
particular not an Enterprise JavaBean.


A JavaBean is a POJO


Note
:
-

1. A JavaBean is a single class, an Enterprise JavaBean is NOT a single class but an entire
component model consisting a group of classes.


2. Data transfer object (DTO), also known as value objects or VO, is a design pattern used
to transfer data between software application subsystems. A JavaBean can be used as a
DTO. DTOs improve performance and maintainability.







XML


Extensible Markup Language (XML) is a set of rules for
encoding documents &
data
in machine
-
readable form.


It is defined in the XML 1.0 Specification produced by the W3C.


Well
-
formed:
Syntactically correct. All XML documents should be well
-
formed.


Contains only properly encoded legal Unicode characters e.g.

<?xml version="1.0" encoding="UTF
-
8"?>


There is a single "root" element which contains all the other elements.

<
users
>


<user>…</user>

</
users
>


The begin, end, and empty
-
element tags which delimit the elements are correctly nested, with
none missing and none overlapping.

A mal
-
formed xml

<
users
>


<user>…</
users
>

</user>


The element tags are case
-
sensitive; the beginning and end tags must match exactly.

A mal
-
formed xml

<
Users
>


<user>…</user>

</
users
>







XML, DTD, XSD (Contd…)


Valid:
Semantically correct i.e. conforms to the grammatical rules. Optional, based on the
requirement.


DTD: Document type definition

XSD: XML Schema definition

Oldest method of validating XML documents

More recent method of validating XML documents

DTDs provide a very weak specification language

e.g.
You can’t put any restrictions on text content

V敲礠p潷o牦u氺lX卄S杩g敳eX潵omuch m潲攠c潮瑲潬 潶敲e
s瑲Wc瑵r攠慮T c潮W敮W

M呄猠Tav攠瑨e楲i潷n n潮
-
塍䰠b慳敤 f潲maW

P敬e
-
f潲m敤

塍X

T漠ref敲eW漠愠M呄T楮⁡渠i䵌MT潣om敮琬 瑨攠eef敲敮c攠
g潥猠
before

the root element:

<?xml version="1.0"?>

<!DOCTYPE
rootElement

SYSTEM "
url
">

<
rootElement
> ... </
rootElement

To refer to an XML Schema in an XML document, the
reference goes
in

the root element:

<?xml version="1.0"?>

<
rootElement


xmlns:xsi
="http://www.w3.org/2001/XMLSchema
-
instance"


(The
X
ML
S
chema
I
nstance reference is
required)


xsi:noNamespaceSchemaLocation
="
url
.xsd">


(This is where
your

XML Schema definition can
be found)


...

</
rootElement
>






XML, DTD, XSD (Contd…)

DTD: Document type definition

XSD: XML Schema definition

Sample DTD:
eternalyfe.dtd

<?xml version="1.0" encoding="UTF
-
8"?>

<!ELEMENT users (user)>

<!ELEMENT user (
id,name
)>

<!ELEMENT id EMPTY>

<!ATTLIST id


value CDATA #REQUIRED


>

<!ELEMENT name (#PCDATA)>

Sample XSD
: eternalyfe.xsd

<?xml version="1.0" encoding="UTF
-
8"?>

<
xsd:schema

xmlns:xsd
="http://www.w3.org/2001/XMLSchema"


targetNamespace
="http://xml.netbeans.org/schema/eternalyfe"


xmlns:tns
="http://xml.netbeans.org/schema/eternalyfe"


elementFormDefault
="qualified">


<
xsd:element

name="name" type="
xsd:string
"></
xsd:element
>


<
xsd:element

name="id" type="
xsd:integer
"></
xsd:element
>


<
xsd:element

name="user">


<
xsd:complexType

>


<
xsd:sequence
>


<
xsd:element

ref="
tns:id
"/>


<
xsd:element

ref="
tns:name
"/>


</
xsd:sequence
>


</
xsd:complexType
>


</
xsd:element
>


<
xsd:element

name="users">


<
xsd:complexType
>


<
xsd:sequence
>


<
xsd:element

ref="
tns:user
"
maxOccurs
="unbounded">


</
xsd:element
>


</
xsd:sequence
>


</
xsd:complexType
>


</
xsd:element
>

</
xsd:schema
>

Sample XML document
:

<?xml version="1.0" encoding="UTF
-
8"?>

<!DOCTYPE users SYSTEM "eternalyfe.dtd">

<users>


<user>


<id value="
aaa
"/>


<name>
jesse
</name>


</user>

</users>

Sample XML document
:

<?
xml version="1.0" encoding="UTF
-
8"?>

<users
xmlns
=
http://xml.netbeans.org/schema/eternalyfe

xmlns:xsi
="http://www.w3.org/2001/XMLSchema
-
instance"

xsi:schemaLocation
="http://xml.netbeans.org/schema/eternalyfe eternalyfe.xsd">


<user>


<id>1</id>


<name>
jesse
</name>


</user>

</users>





XML, DTD, XSD (Contd…)


More Details on DTD and XSD:


Reference 1


Reference 2





Spring Framework


URL:
http://www.springsource.org/



Framework
: A reusable set of libraries or classes for building software
systems



Spring Framework is one of the most popular and stable
framework
for
enterprise application development


Ubiquitous for Java development


Well established in enterprise Java apps


Time tested and proven reliable


Available for Java and .NET



Primary purpose is to reduce dependencies i.e. loose coupling



Considered an alternative / replacement for the Enterprise JavaBean (EJB)
model








Spring Framework (Contd…)

Did we really need yet another Java framework?


JavaEE does a fine job of
standardizing low
-
level infrastructure

but is not
and easily usable view for application code



Many JavaEE applications in practice are
overly complex
and take
excessive effort to develop and maintain



EJB is hard, JNDI is non
-
intuitive, JDBC is verbose and you need to know
another language SQL, etc.



Much of JavaEE
development is configuration, setup and “plumbing” code i.e.
even to do very simple things, you have to write lot of lines of code





Spring Framework (Contd…)

Spring aims to make JavaEE development easier:


Spring provides enterprise services to Plain Old Java Objects (POJOs).


Spring has a nice balance between constraint and freedom. A good framework should
provide guidance with respect to good practice, but should not be overly restrictive and
constraining developers in inappropriate ways.


Modules of the Framework


IOC (Inversion of Control) Container


Aspect
-
Oriented Programming Framework (AOP)


Data access abstraction and JDBC simplifications


Transaction Management


MVC web framework


Simplification for working with J2EE APIs such as JNDI, JTA, etc.


Lightweight remoting, JMS support, JMX support


Support for a comprehensive testing strategy for application developers





Spring Framework (Contd…)






Spring Framework (Contd…)


Inversion of Control (IoC)
The Hollywood Principle, “Don’t call
us, we’ll call you.” Also known as Dependency Injection.



Without Spring

With Spring












Direct Coupling between Class

A/B
-
Class C












Loose Coupling between Class

A/B
-
Class C


Class A and Class B are aware of Class C through its
interface

Class A

Class C

Class B

Spring Container

Class C

Class A

Class B





Model















Architecture recap

Presentation Tier

Business Tier

Persistence Tier

Controller 1

Controller 2

Views

BO1

(Business Object)

BO2

BO3

DAO1

(Data
Access
Object)

DAO2


Hibernate

Spring





Model















IOC/DI based Architecture

Presentation Tier

Business Tier

Persistence Tier

Controller 1

Controller 2

Views

BO1

(Business Object)

BO2

BO3

DAO1

(Data
Access
Object)

DAO2

Spring

DB connection(Session)
factory

DAO1,
DAO2

DAO1,
BO3

DAO2

BO1,
BO2

BO3





Types of Injection

Constructor Injection

Setter Injection

The
Spring IOC

container will inject the dependencies
using constructor.

The
Spring IOC

container will inject the dependencies
using the setter.

Based on number of dependencies required, the
constructor takes arguments.

Based on number of dependencies required, those

many
setters are used.

Use when
: As all the dependencies are resolved only once

at the time of invoking the constructor, you can’t
r散潮晩杵r攠瑨e b敡e 污W敲. 䡥Hc攠畳攠楴iW漠

慳a楧i
c潮晩杵r慢汥lc潮oW慮瑳Wv慬a敳ef
潲 X潵爠慰p汩la瑩潮W

Use when
: If you don't have requirement to inject all the
dependencies, use
this technique
to configure beans in a
more flexible manner.


e.g.


<bean class="
java.lang.String
">


<constructor
-
arg

index="0" value="Admin"/>


</bean>


e.g.



<!
--

Error Codes
--
>


<bean id="errors" class="
java.util.HashMap
">


<constructor
-
arg
>


<map>


<entry key="NODATA" value="1001:No data found"/>


<entry key="DATAERROR" value="5555:We are unable to
complete your request due to technical difficulties in our back
-
end
systems. Please wait for a few minutes and try again
-

If problem
persists, please contact our system administrators. We apologize for
the inconvenience."/>


</map>


</constructor
-
arg
>


</bean>

e.g.

<bean id="
addressBean
"
class="
com.eternalyfe.edu.beans.Address
">


<property name="street">


<value>19,
V.K.Joag

Path</value>


</property>


<property name="city">


<value>
Pune
</value>


</property>


<property name="
pincode
">


<value>411001</value>


</property>

</bean>





Spring Framework (Contd…)

Singleton bean scope

Prototype

bean scope

Only one
shared

instance of the bean will
be managed.

Results in the creation of a
new instance

every time a request for that specific bean
is done.

Most of the times Singleton mode is
needed.


This is the default bean scope.

Relatively less frequently

needed.

e.g.

all the injections in our architecture


e.g. Templates based on Spring such as
Email templates

<bean

id="
customerService
"
class=“
com.eternalyfe.services.CustomerService

/>


<bean

id="
customerService
"
class="
com.eternalyfe.services.Email

Service"
scope="prototype"
/>


Bean scope: is used to decide which type of bean instance should be returned
to the caller.






Spring Framework (Contd…)


Two of the most fundamental and important packages in Spring are the
org.springframework.beans

and
org.springframework.context

packages



Code in these packages provides the basis for Spring's
DI

features



The
BeanFactory

provides a configuration mechanism capable of managing
beans (objects) of any nature, using potentially any kind of storage facility. i.e.
BeanFactory provides the configuration framework and basic functionality



The
ApplicationContext

builds on top of the BeanFactory (it's a subclass) and
adds other functionalities such as easier integration with Spring’s AOP features,
message resource handling (for use in internationalization), application
-
layer
specific contexts such as the WebApplicationContext i.e.
ApplicationContext
adds enhanced capabilities to it, some of them more J2EE and enterprise
-
centric





Example 1: Constructor and Setter Injection

Address.java

package com.eternalyfe.springstudy1.beans;

import java.io.Serializable;

public class Address implements Serializable{


private String street;


private String city;


private String state;


private String pincode;



/**


* @return the street


*/


public String getStreet() {


return street;


}



/**


* @param street the street to set


*/


public void setStreet(String street) {


this.street = street;


}


//setters
-
getters for city, state and pincode

}






Example 1: Constructor and Setter Injection (Contd…)

College.java

package com.eternalyfe.springstudy1.beans;

import java.io.Serializable;

public class College implements Serializable{


private String name;


private Address address;


//Constructor


public College (String name, Address address)


{


this.name = name;


this.address = address;


}


/**


* @return the address


*/


public Address getAddress() {


return address;


}


/**


* @param address the address to set


*/


public void setAddress(Address address) {


this.address = address;


}


//Setter
-
getter for name

}







Example 1: Constructor and Setter Injection (Contd…)

applicationContext.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.5.xsd">


<bean id="wadiaCollegeAddress" class="com.eternalyfe.springstudy1.beans.Address">


<!
--

setter injection
--
>


<property name="street">


<value>19, V.K.Joag Path</value>


</property>


<property name="city">


<value>Pune</value>


</property>


<property name="pincode">


<value>411001</value>


</property>


</bean>


<bean id="wadiaCollegeBean" class="com.eternalyfe.springstudy1.beans.College">


<!
--

constructor injection
--
>


<constructor
-
arg index="0" type="java.lang.String"
value=
"Nowrosjee Wadia College"/>


<constructor
-
arg index="1">


<
ref
bean="wadiaCollegeAddress"/>


</constructor
-
arg>


</bean>

</beans>





Example 1: Constructor and Setter Injection (Contd…)

DependencyInjection.java:

package com.eternalyfe.springstudy1;


import com.eternalyfe.springstudy1.beans.Address;

import com.eternalyfe.springstudy1.beans.College;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.FileSystemResource;

import org.springframework.core.io.Resource;


public class DependencyInjection {


public static void main(String args[]){


Resource xmlResource = new FileSystemResource("applicationContext.xml");


BeanFactory factory = new XmlBeanFactory(xmlResource);


College wadiaCollegeBean = (College)factory.getBean("wadiaCollegeBean");


Address address = wadiaCollegeBean.getAddress();


System.out.println(wadiaCollegeBean.getName());


System.out.println(address.getCity());


System.out.println(address.getStreet());


System.out.println(address.getPincode());


System.out.println(address.getState());


}

}








Example 1: Constructor and Setter Injection (Contd…)

DependencyInjectionApplicationContext.java:

package com.eternalyfe.springstudy1;


import com.eternalyfe.springstudy1.beans.Address;

import com.eternalyfe.springstudy1.beans.College;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;


public class DependencyInjectionApplicationContext {


public static void main(String args[]){


ApplicationContext context =




new ClassPathXmlApplicationContext(new String[] {"applicationContext_college.xml"});




College wadiaCollegeBean = (College)context.getBean("wadiaCollegeBean");


Address address = wadiaCollegeBean.getAddress();


System.out.println(wadiaCollegeBean.getName());


System.out.println(address.getCity());


System.out.println(address.getStreet());


System.out.println(address.getPincode());


System.out.println(address.getState());


}

}



Note:
-

Copy applicationContext.xml as applicationContext_college.xml to the default package








Assignment


Introduce a collection of Colleges using
java.util.HashMap


Iterate through the collection and display the
college details


Implement using both BeanFactory and
ApplicationContext






Bean Life
-
cycle methods

Init method

The init method runs AFTER all bean dependencies are loaded


Constructor loads when the bean is first instantiated


Allows the programmer to execute code once all dependencies are present

e.g.


public class
ExampleBean

{

public void init() {


// do something

}

}



<bean id="
exampleBean
" class=”
org.example.ExampleBean
"


init
-
method=”init” />

Destroy method

Allows the programmer to explicitly release

any resources and cleanup before the bean is
removed from Spring container e.g. deletion of temporary data or files

public class
ExampleBean

{

public void
cleanUp
() {


// do something

}

}



<bean id="
exampleBean
" class=”
org.example.ExampleBean
"


destroy
-
method=”
cleanUp
” />





Beans more…


Abstract (parent) beans: Allows definition of part of a bean
which can be reused many times in other bean definitions


<bean id="studymaterial"
abstract="true"


class="com.eternalyfe.StudyMaterial">


<property name="media" value="PPT"/>


<property name="download_available"
value="yes"/>


<property name=“project_code_available"
value=“no"/>

</bean>


<bean id="javastudymaterial"


class="com.eternalyfe.JavaStudyMaterial"


parent="studymaterial"
>


<property name="project_code_available"
value="yes"/>

</bean>


The parent bean (studymaterial)
defines 3 values (
media
,
download_available,
project_code_available
)


These
are the default values


The child bean (javastudymaterial)
uses the parent’s media and
download_available values


The child bean (javastudymaterial)
overrides the parent’s
project_code_available value


Parent can not not be injected, but
child can be





Beans more…

Anonymous
vs

ID

With ID: This bean is identified (has an id)
and can be accessed to inject it into
another bean








Anonymous: Beans that do not need to be
referenced elsewhere can be defined
anonymously


<bean
id="
wadiaCollegeAddress
"
class="com.eternalyfe.springstudy1.
beans.Address">


<!
--

setter injection
--
>


<property name="street">


<value>1999999,
V.K.Joag

Path</value>


</property>

</bean>



<bean
class="com.eternalyfe.springstudy1.
beans.Address">


<!
--

setter injection
--
>


<property name="street">


<value>1999999,
V.K.Joag

Path</value>


</property>

</bean>






Beans more…

Inner

Bean

If there’s no need to share data among
multiple beans, a bean can be made an
inner bean i.e. defined locally





<bean id="
wadiaCollegeBean
"
class="com.eternalyfe.springstudy1.
beans.College">


<property
name="address">


<bean
class="com.eternalyfe.springstudy1.
beans.Address">


<property name="street">


<value>1999999,
V.K.Joag

Path</value>


</property>


</bean>


</property>

</bean>





AOP
-
Aspect Oriented Programming


Complements OO programming
:
OO

decomposes applications into a
hierarchy of
objects

while
AOP

decomposes programs into
aspects



An aspect is a concern that cuts across multiple objects and often
duplicated in many classes. Some examples:


Aspect

Remarks

Logging

Applicable to all tiers

Transaction Management

Applicable to Business tier + Persistence tier

Exception Handling

Applicable to all tiers

Caching

Applicable to all tiers

Locking

Applicable to Persistence tier

Security

Applicable to all tiers

Performance Monitoring

Applicable to all tiers





AOP (Contd…)

Some existing AOP frameworks:


ASM: a lightweight bytecode translator.


AspectJ: an AO source
-
level weaver. New Language.


AspectWerkz: an AO framework (bytecode
-
level dynamic weaver+configuration).


BCEL: a bytecode translator.


CGLIB: high
-
level API for class artifact manipulation and method interception.


JAC: an AO middleware (bytecode
-
level dynamic weaver+configuration+aspects).
Framework.


Javassist: a bytecode translator with a high
-
level API.


JBoss
-
AOP: interception and metadata
-
based AO framework.


JMangler: a bytecode translator with a composition framework for translations.


Nanning: an AO weaver (framework).


Prose: an AO bytecode
-
level dynamic weaver (framework).


… still more





AOP (Contd…)


AOP Alliance is Java/J2EE AOP standards
:
AOP Alliance is an open source project
with the main goals of promoting:


Adoption of AOP


Interoperability among different AOP implementations with the help of interfaces
and components that are well defined


Package:
org.aopalliance


org.springframework.aop
: Core Spring AOP interfaces, built on AOP
Alliance interoperability interfaces



AspectJ


Original AOP technology (first version in 1995)


Offers a full
-
blown Aspect Oriented Programming language


Spring integrates with AspectJ through the package:
org.springframework.aop.aspectj








AOP (Contd…)



Aspects can be added or removed as needed without changing your code.



Two approaches for AOP:


Approach 1
: Schema
-
based configuration (classic style, supported in all versions)


Approach 2
: Annotations (introduced in Spring 2.0)


We’ll use
Approach 1
, primarily because by experience we have found that the
maintainability and troubleshooting of application is easier:


Your Java classes stay focussed on implementing the application
-
specific code and
hence continue to be POJOs


You don’t have to learn yet
-
another language, in this case, the annotations
-
based
AspectJ language






AOP (Contd…)

In Spring, aspects are woven into Spring
-
managed beans at
runtime

by wrapping
them with a proxy class.


Spring aspects are implemented as
proxies that wrap the target object
.


The proxy handles:



Method calls



Performs additional aspect logic



Then invokes the target method.


Spring does not create the proxied object until it is needed by the application i.e. lazy
initialization





AOP example: Performance monitoring


Learning AOP by example: Performance monitoring


Weaving
: is the
process of
combining or
assembling the
cross
-
cutting
concern’s code with
the rest of your
application


AspectJ

uses
compile
time
weaving i.e. byte
code modification.


Spring Aspects
are
weaved together at
runtime

using
dynamic
proxies
.





AOP example: Performance monitoring (Contd…)


Goal: Measure the performance of business methods used by an application


Let us implement by using AOP Alliance



Step 1: Define the Business Interface

package com.eternalyfe.springstudy1.service;


import com.eternalyfe.springstudy1.beans.College;


public interface IBiz {


public void display(College collegeBean);


public void list(String country);

}






AOP example: Performance monitoring (Contd…)


Step 2: Define the BO by implementing the Business Interface

package com.eternalyfe.springstudy1.service;

//appropriate import statements

public class BizSample implements IBiz {


private Map colleges;


//setter
-
getter for colleges


public void display(College collegeBean) {


Address address = collegeBean.getAddress();


//Display the address details say using System.out.println


}


public void list(String country) {


System.out.println("
\
n==>Country=" + country);


Iterator itr = colleges.values().iterator();


while (itr.hasNext()) {


College collegeBean = (College) itr.next();


display(collegeBean);


System.out.println("***********");


try {


Thread.sleep(1800); //artificial delay


} catch (InterruptedException ex) {


}


}


}

}





AOP example: Performance monitoring (Contd…)


Step 3: Wire the BO in spring and inject the dependencies


<!
--

Define the Business Object
--
>


<bean id="bizSample" class="com.eternalyfe.springstudy1.service.BizSample">


<property name="colleges" ref="colleges"/>


</bean>



Step 4: Define the Aspect using AOPAlliance

package com.eternalyfe.springstudy1.aop;

import org.aopalliance.intercept.*;

import org.springframework.util.StopWatch;

public class PerformanceMonitorDetailInterceptor implements MethodInterceptor {


public Object invoke(MethodInvocation invocation) throws Throwable {



String name = invocation.getMethod().getDeclaringClass().getName()





+ "." + invocation.getMethod().getName();



StopWatch sw = new StopWatch(name);



sw.start(name);



Object rval = invocation.proceed();



sw.stop();



System.out.println(sw.prettyPrint());



return rval;


}

}






AOP example: Performance monitoring (Contd…)


Step 5:
Spring allows method interception. This means when a method is called the framework
can attach functionality.
Define the advisor or interceptor: Associate advice (aspect code) with
point cut.


<bean id="performanceAdvisor"



class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">



<property name="advice">


<bean class="com.eternalyfe.springstudy1.aop.PerformanceMonitorDetailInterceptor"/>


</property>



<!
--

point cut
--
>


<property name="patterns">


<list>


<value>.*list.*</value>


<value>.*find.*</value>


<value>.*save.*</value>


<value>.*update.*</value>


</list>


</property>

</bean>





AOP example: Performance monitoring (Contd…)


Step 6: Define proxy to associate advisor with BO

<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">


<property name="beanNames">


<value>bizSample</value>


</property>


<property name="interceptorNames">


<list>


<value>performanceAdvisor</value>


</list>


</property>


</bean>






AOP example: Performance monitoring (Contd…)


Step 7: Run

package com.eternalyfe.springstudy1;

//import statements

public class DependencyInjectionApplicationContext {


public static void main(String args[]) {


ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]{"com
\
\
eternalyfe
\
\
springstudy1
\
\
config
\
\
applicationContext_college_aopalliance.xml"});


IBiz bizSample = (IBiz) context.getBean("bizSample");


System.out.println("
\
n
\
n########### Iterating through colleges ########");


bizSample.list("INDIA");



Map colleges = (Map)context.getBean("colleges");


College wadiaCollege = (College)colleges.get("WADIA");


System.out.println("
\
n
\
n########### Displaying Wadia college data ########");


bizSample.display(wadiaCollege);


}

}


Now comment out the code to display wadiaCollege bean data. Even though bizSample’s list method internally uses
display method, you will find that the performance of display method does not get monitored, if called
internally. This is because when an internal call is made, the proxy is not used.







AOP Concepts

Join point

A point during program execution, such as a method executing or an exception being
handled,

where aspects can be joined or attached.


In Spring AOP, a join point exclusively pertains to method execution only (I.e. does not
support Field interception), which could be viewed as a limitation of Spring AOP.
However, in reality, it is enough to handle most common cases of implementing
crosscutting concerns.


Pointcut

Description of the collection of methods to which

the cross
-
cutting concern
has to be applied.


A declarative condition that identifies the join points for consideration during
an execution run.
Pointcut

is specified as an expression.

Advice

It’s
W桥h扬潣o映c潤攠W桡W r畮猠u慳敤渠W桥h
灯pnW捵c

摥fi湩Wi潮o IW i猠
information about "when" an aspect is to be executed with respect to the join
point. Examples of types of advice are "around," "before,“ ,"after" and
“throws”. They specify when the aspect's code will execute with respect to a
灡rWi捵污r 橯j渠灯nnW.


AOP Proxies

Surrogate object that invokes advice and advises the invoked class





AOP Concepts (Contd…)

Proxy


Target

Object

Advice


Advisor


Pointcut






AOP Advices


Around advice (
implements org.aopalliance.intercept.MethodInterceptor
)


Execute code before and after joinpoint


AOP Alliance compliant


Must call invocation.proceed() to call target


Implements AroundAdvice

Object invoke(MethodInvocation invocation) {


// change arguments, start transaction, lock, etc.


invocation.proceed();


// change return value, stop transaction, unlock,etc.


}



Throws advice
(implements org.springframework.aop.ThrowsAdvice)


Executes code if exception is thrown


Implements
ThrowsAdvice


void afterThrowing(Method method, Object[] args, Object target, Throwable subclass) throws
Exception






AOP Advices (Contd…)


Method before

(implements org.springframework.aop.
MethodBeforeAdvice
)


Executes before joinpoint, cannot stop execution


Implements MethodBeforeAdvice


void before(Method m, Object[] args, Object target) throws Throwable


Cannot alter return type



Method after returning
(implements org.springframework.aop.

AfterReturningAdvice
)


Executes code after normal joinpoint execution


Implements
AfterReturningAdvice


void afterReturning(Object object, Method m, Object[] args,
Object target) throws Throwable


Cannot modify return value





Spring
-
AspectJ integration:

AOP using an arbitrary class as an Advice


Step 1: Define the Advice


no need to implement any interface

package com.eternalyfe.springstudy1.aop;

// import statements

public class SimpleProfiler {


public void myAfterMethod() throws Throwable {


System.out.println("After the method call :: " + logTimeStamp());


}


public void myBeforeMethod() {


System.out.println("Before the method call :: " + logTimeStamp());


}

/* Convert Time value to a specific format of date/time */


String logTimeStamp() {


String result = "";


DateFormat sdf_output = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");


try {


result = sdf_output.format(new Date().getTime());


} catch (Exception ex) {}


return result;


}

}





Spring
-
AspectJ integration:

AOP using an arbitrary class as an Advice (Contd…)


Step 2: Wire aspect using Spring Configuration

applicationContext_college_aop.xml:

<beans xmlns="http://www.springframework.org/schema/beans"


xmlns:xsi="http://www.w3.org/2001/XMLSchema
-
instance"


xmlns:aop="http://www.springframework.org/schema/aop"


xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring
-
beans
-
2.5.xsd


http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring
-
aop
-
2.5.xsd
">


. . .


<bean id="profiler" class="com.eternalyfe.springstudy1.aop.SimpleProfiler"/>


<aop:config>


<aop:aspect ref="profiler">


<!
--

specific method


<aop:pointcut id="profilerPointcutBefore" expression="execution(* com.eternalyfe.springstudy1.service.IBiz.list(Str
ing)))" />


--
>


<!
--

specific package
--
>


<aop:pointcut id="profilerPointcutBefore" expression="within(com.eternalyfe.springstudy1.service..*)" />


<aop:before method=“myBeforeMethod" pointcut
-
ref="profilerPointcutBefore"/>



<aop:pointcut id="profilerPointcutAfter" expression="within(com.eternalyfe.springstudy1.service..*)" />


<aop:after method=“myAfterMethod" pointcut
-
ref="profilerPointcutAfter"/>


</aop:aspect>


</aop:config>

</beans>






AspectJ Pointcut Expressions


An AspectJ pointcut declaration in Spring has two parts:


A signature comprising a name and any parameters, and


A pointcut expression that determines exactly which method executions we are
interested in.


execution

For matching method execution join points, this is the primary
pointcut

designator you
will use when working with Spring AOP

within

limits matching to join points within certain types

this

limits matching to join points where the bean reference is an instance of the given type

target

limits matching to join points where the target object is an instance of the given type

args

limits matching to join points where the arguments are instances of the given types





AspectJ Pointcut Expressions examples

Following are the examples showing different manner in which a pointcut can be
declared:


the execution of any public method:

execution(public * *(..))



the execution of any method with a name beginning with “set”:

execution(* set*(..))



the execution of any method defined by the MyService interface

execution(* com.xyz.service.MyService.*(..))



the execution of any method defined in the service package:

execution(* com.xyz.service.*.*(..))



the execution of any method defined in the service package or a sub
-
package:

execution(* com.xyz.service..*.*(..))



any join point within the service package:

within(com.xyz.service.*)






AspectJ Pointcut Expressions examples


any join point within the service package or a sub
-
package:

within(com.xyz.service..*)



any join point where the proxy implements the AccountService interface:

this(com.xyz.service.AccountService)



any join point where the target object implements the AccountService interface:

target(com.xyz.service.AccountService)



any join point which takes a single parameter, and where the argument passed at runtime
is Serializable:

args(java.io.Serializable)




Pointcut expressions can also be
combined using ‘&&’, ‘||’ and ‘!’