Você está na página 1de 30

Aspect Oriented Programming

with
Spring
Problem area

How to modularize concerns that span multiple classes


and layers?

Examples of cross-cutting concerns


!
"ransaction management
!
#ogging
!
Profiling
!
Security
!
$nternationalisation
#ogging A nai%e approach
public class HibernateE%ent&AO
'
pri%ate static #og log ( #og)actory*get#og+ HibernateE%ent&AO*class ,-
public $nteger sa%eE%ent+ E%ent e%ent ,
'
log.info+ .Executing sa%eE%ent+ E%ent , with argument / . e%ent*toString+, ,-
Session session ( session0anager*get1urrentSession+,-
return +$nteger, session*sa%e+ e%ent ,-
2
public E%ent getE%ent+ $nteger id ,
'
log.info+ .Executing getE%ent+ int ,. ,-
Session session ( session0anager*get1urrentSession+,-
return +E%ent, session*get+ E%ent*class3 id ,-
2
4etrie%ing log
instance
#ogging method
executions
#ogging A nai%e approach
E%ent0anager
E%ent&AO
Ser%ice layer
Persistence layer
$n%o5es methods on
the &AOs
Person&AO
&AOs perform
both logging and
persistence
operations
+method in%ocation,
Shortcomings of nai%e approach

0ixes persistence and logging functionality


! 6iolates the principle of separation of concerns
! $ncreases complexity and inter7dependency

$n%ol%es repetition of code


!
6iolates the DRY principle
!
0a5es it difficult to change

1ouples the #og)actory to the HibernateE%ent&AO


!
Pre%ents loosely coupled design
!
0a5es change3 re7use and testing problematic
#ogging "he AOP approach
E%ent0anager
E%ent&AO
Ser%ice layer
Persistence layer Person&AO
&AOs perform
persistence only
AOP interceptor
$ntercepts method
in%ocations and
performs logging
+method in%ocation,
Ad%antages of AOP approach

Separates persistence and logging functionality


! "he logging concern ta5en care of by the interceptor
! 0a5es it easier to understand3 manage and debug

Promotes code reuse and modularization


!
"he AOP interceptor is used by all methods in the &AOs
!
0a5es it easier to change

&ecouples the #og)actory from the &AO impl8s


!
"he HibernateE%ent&AO is unaware of being logged
!
0a5es change3 re7use and testing simple
Aspect Oriented Programming

&efinition Enables encapsulation of functionality that


affects multiple classes in separate units

1omplements ob9ect oriented programming

0ost popular implementation for :a%a is AspectJ


!
Aspect oriented extension for :a%a
!
;ased on Eclipse3 a%ailable as plugin and stand7alone
Spring o%er%iew
AOP with Spring

"he AOP framework is a 5ey component of Spring


! Pro%ides declarati%e enterprise ser%ices +transactions,
! Allows for custom aspects

Aims at pro%iding integration between AOP and $o1

$ntegrates ! but doesn8t compete ! with Aspect:

Pro%ides two techni<ues for defining aspects


! =Aspect: annotation
! >0# schema7based
AOP concepts

Aspect
! A concern that cuts across multiple classes and layers

:oin point
! A method invocation during the execution of a program

Ad%ice
!
An implementation of a concern represented as an interceptor

Pointcut
!
An expression mapped to a 9oin point
=Aspect: support

Style of declaring aspects as regular :a%a classes with


:a%a ? annotations

4e<uires aspectweaver and aspectrt on the classpath

Enabled by including the following information in the


Spring configuration file
@beans xmlns(AhttpBBwww*springframewor5*orgBschemaBbeansA
xmlnsxsi(AhttpBBwww*wC*orgBDEEFB>0#Schema7instanceA
xmlns:aop="http://www.springframework.org/schema/aop"
xsischema#ocation(A
httpBBwww*springframewor5*orgBschemaBbeans httpBBwww*springframewor5*orgBschemaBbeansBspring7beans7D*E*xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

<aop:aspectj-atoprox!/>
&eclaring an aspect
@bean id(Alogging$nterceptorA
class(Ano*uio*inf?G?E*interceptor*#ogging$nterceptorABH
import org*aspect9*lang*annotation*Aspect-
"#spect
public class #ogging$nterceptor
'
BB ***
2
=Aspect annotation
Any bean with a class
annotated as an aspect
will be automatically
detected by Spring
4egular bean definition
pointing to a bean class
with the =Aspect
annotation

A concern that cuts across multiple classses and layers


&eclaring a pointcut

An expression mapped to a oin point +method


in%ocation,
=Aspect
Public class #ogging$nterceptor
'
"$ointct+ Aexecution+ I no*uio*inf?G?E*dao*I*I+**, ,A ,
pri%ate %oid dao#ayer+, '2
$ndicated by the
=Pointcut annotation
Pointcut signature pro%ided by
a regular method definition
Aspect: pointcut expression that determines
which method executions to intercept
Pointcut expression pattern

"he execution pointcut designator is used most often


designator+ modifiers return7type declaring7type name+params, throws ,
Pointcut
designator*
0andatory*
1an use I to
match any type*
0andatory*
Public3 pri%ate3
etc* Optional*
Pac5age and
class name*
Optional*
0ethod name*
1an use I to
match any type*
0andatory*
+, ( no params*
+**, ( any nr of params*
+I3String, ( one of any
type3 one of String*
Exception type*
Optional*
Pointcut expression examples
execution+ public I I+**, , Any public method
execution+ public I no*uio*inf?G?E*dao*I*I+**, ,
Any public method defined
in the dao pac5age
execution+ I sa%eI+**, ,
Any method with a name
beginning with save
execution+ I no*uio*inf?G?E*dao*E%ent&AO*I+I, ,
Any method defined by the
E%ent&AO interface with one param
&eclaring ad%ice

$mplementation of concern represented as an interceptor

"ypes
!
;efore ad%ice
!
After ad%ice
!
Around ad%ice
;efore ad%ice*
Executes before the
matched method*
&eclared using the
=;efore annotation*
=Aspect
public class #ogging$nterceptor
'
"%efore+ .no*uio*inf?G?E*interceptor*#ogging$nterceptor*dao#ayer+,. ,
public %oid intercept+ :oinPoint 9oinPoint ,
'
log*info+ .Executing . / 9oinPoint*getSignature+,*toShortString+, ,-
2
Pro%ides access to the
current 9oin point +target ob9ect3
description of ad%ised method3 ect* ,
After returning J throwing ad%ice
After returning ad%ice*
Executes after the
matched method has
returned normally*
&eclared using the
=After4eturning
annotation*
=Aspect
public class #ogging$nterceptor
'
"#fter&etrning+ .no*uio*inf?G?E*interceptor*#ogging$nterceptor*dao#ayer+,. ,
public %oid intercept+ :oinPoint 9oinPoint ,
'
log*info+ .Executed successfully . / 9oinPoint*getSignature+,*toShortString+, ,-
2
After throwing ad%ice*
Executes after the
matched method has
thrown an exception*
&eclared using
=After"hrowing*
=Aspect
public class #ogging$nterceptor
'
"#fter'hrowing+ .no*uio*inf?G?E*interceptor*#ogging$nterceptor*dao#ayer+,. ,
public %oid intercept+ :oinPoint 9oinPoint ,
'
log*info+ .Execution failed . / 9oinPoint*getSignature+,*toShortString+, ,-
2
Around ad%ice
Around ad%ice*
"he first parameter
must be of type
Proceeding:oinPoint !
calling proceed+, causes
the target method to
execute*
&eclared using the
=Around annotation*
=Aspect
public class #ogging$nterceptor
'
"#rond+ .no*uio*inf?G?E*interceptor*#ogging$nterceptor*dao#ayer+,. ,
public %oid intercept+ Proceeding:oinPoint 9oinPoint ,
'
log*info+ .Executing . / 9oinPoint*getSignature+,*toShortString+, ,-
try
'
9oinPoint*proceed+,-
2
catch + "hrowable t ,
'
log*error+ t*get0essage+, / . . / 9oinPoint*getSignature+,*toShortString+, ,-
throw t-
2
log*info+ .Successfully executed . / 9oinPoint*getSignature+,*toShortString+, ,-
2

1an do wor5 both before and after the method executes

&etermines when3 how and if the method is executed


Accessing arguments

"he args !inding form ma5es argument %alues a%ailable


to the ad%ice body

Argument name must correspond with ad%ice method


signature
=Aspect
public class #ogging$nterceptor
'
=;efore+ .no*uio*inf?G?E*interceptor*#ogging$nterceptor*dao#ayer+, and . /
.args+ o(ject3 ** ,. ,
public %oid intercept+ :oinPoint 9oinPoint3 Ob9ect o(ject ,
'
log*info+ .Executing . / 9oinPoint*getSignature+,*toShortString+, /
. with argument . / ob9ect*toString+, ,-
2
0a5es the ob9ect
argument a%ailable
to the ad%ice body
Kill restrict matching
to methods declaring
at least one parameter
Accessing return %alues

"he returning !inding form ma5es the return %alue


a%ailable to the ad%ice body

4eturn %alue name must correspond with ad%ice method


signature
=Aspect
public class #ogging$nterceptor
'
=After4eturning+
pointcut(.no*uio*inf?G?E*interceptor*#ogging$nterceptor*dao#ayer+, .3
returning(.o(ject. ,
public %oid intercept+ :oinPoint 9oinPoint3 Ob9ect o(ject ,
'
log*info+ .Executed . / 9oinPoint*getSignature+,*toShortString+, /
. with return %alue . / ob9ect*toString+, ,-
2
0a5es the ob9ect
return %alue
a%ailable to the
ad%ice body
Kill restrict matching
to methods returning a
%alue of specified type
Schema7based support

#ets you define aspects using the aop namespace tags


in the Spring configuration file

Enabled by importing the Spring aop schema

Pointcut expressions and ad%ice types similar to


=Aspect:

Suitable when
!
Lou are unable to use :a%a ?
! Prefer an >0# based format
! Lou need multiple 9oinpoints for an ad%ice
&eclaring an aspect

An aspect is a regular :a%a ob9ect defined as a bean in


the Spring context
Aspect declared using
the "aop#aspect$
element* ;ac5ing bean
is referenced
with the ref attribute*
@aopconfigH
@aopaspect id(.logging. ref(.logging)nterceptor.H
@BaopaspectH
@BaopconfigH
@bean id(Alogging)nterceptorA
class(Ano*uio*inf?G?E*interceptor*#ogging$nterceptorABH
All configuration inside
an @aopconfigH element
4egular bean definition
&eclaring a pointcut

Pointcut expressions are similar to =Aspect:

A pointcut can be shared across ad%ice


Pointcut declared inside
@aopconfigH element
using the
@aoppointcutH element
@aopconfigH
@aoppointcut id(.dao#ayer.
expression(Aexecution+ I no*uio*inf?G?E*dao*I*I+**, ,.BH

@BaopconfigH
1an also be defined
inside aspects
&eclaring ad%ice
;efore ad%ice*
&eclared inside an
aspect*
@aopaspect id(.logging. ref(.logging$nterceptor.H
@aop:(efore pointcut7ref(.dao#ayer. method(.intercept.BH
@BaopaspectH
public class #ogging$nterceptor
'
public %oid intercept+ :oinPoint 9oinPoint ,
'
BB &o some useful intercepting wor5
2
2
4efers to pointcut 4efers to ad%ising method
Ad%ice is a regular
:a%a class
&eclaring ad%ice
After returning ad%ice
@aopaspect id(.logging. ref(.logging$nterceptor.H
@aop:after-retrning pointcut7ref(.dao#ayer. method(.intercept.BH
@BaopaspectH
After throwing ad%ice
@aopaspect id(.logging. ref(.logging$nterceptor.H
@aop:after-throwing pointcut7ref(.dao#ayer. method(.intercept.BH
@BaopaspectH
Around ad%ice
@aopaspect id(.logging. ref(.logging$nterceptor.H
@aop:arond pointcut7ref(.dao#ayer. method(.intercept.BH
@BaopaspectH
AOP 7 "ransaction 0anagement
"ransaction0anager
interface
public interface "ransaction0anager
'
public %oid enter+,-
public %oid abort+,-
public %oid lea%e+,-
=Aspect
public interface "ransaction$nterceptor
'
=Around+ .execution+ public no*uio*inf?G?E*dao*I*I+**, ,. , BB $n7line pointcut
public %oid intercept+ Proceeding:oinPoint 9oinPoint ,
'
transaction0anager*enter+,-
try
'
9oinPoint*proceed+,-
2
catch + "hrowable t ,
'
transaction0anager*abort+,-
throw t-
2
transaction0anager*lea%e+,-
"ransaction management
implemented with
around ad%ice
Enters transaction
before method in%ocation
Aborts and rolls bac5
transaction if method fails
#ea%es transaction if
method completes norm*
=Aspect: or Schema7based?

Ad%antages of schema style


!
1an be used with any :&M le%el
!
1learer which aspects are present in the system

Ad%antages of =Aspect: style


! One single unit where information is encapsulated for an aspect
! 1an be understood by Aspect: ! easy to migrate later
Summary

Mey components in AOP are aspect3 pointcut3 oin point3


and advice

AOP lets you encapsulate functionality that affects


multiple classes in an interceptor

Ad%antages of AOP
! Promotes separation of concern
! Promotes code reuse and modularization
! Promotes loosely coupled design
4eferences

"he Spring reference documentation 7 1hapter N


! www*springframewor5*org

AOP example code


!
www*ifi*uio*noB$O)?G?EBhEGBunder%isningsplan*xml

Você também pode gostar