Spring AOP
Presented By
SHAKIL AKHTAR
Agenda
v What problem does AOP solve?
v Core AOP concepts.
v Quick Start.
v Defining Pointcuts.
v Implementing Advice.
© Shakil Akhtar
What are Cross-cutting Concerns?
v Generic functionality that’s needed in places in
application.
v Examples
•  Logging
•  Transaction Management
•  Security
•  Caching
•  Error Handling
•  Performance Monitoring
•  Custom Business Rules
© Shakil Akhtar
An Example Requirement
v Perform a role based security check before
every application method.
A cross cutting
concern requirement
© Shakil Akhtar
Implementing Cross-Cutting Concerns
Without Modularization
v Failing to Modularize cross-cutting concerns leads to
two things
•  Code Tangling
o  A couple of concerns
•  Code scattering
o  The same concern spread across modules
© Shakil Akhtar
Symptom #1: Tangling
v Write tangling code
© Shakil Akhtar
Symptom #2: Scattering
v Write scattering code
© Shakil Akhtar
System Evolution Without Modularization
© Shakil Akhtar
How AOP Works
v Implement your mainline application logic
•  Focusing on the core problem
v Write aspects to implement your cross-cutting
concerns
•  Spring provides many aspects
v Weave the aspects into your application
•  Adding the cross cutting concern behavior’s to the right
place
© Shakil Akhtar
Aspect Oriented Programming (AOP )
v Aspect Oriented Programming(AOP) enables
modularization of cross-cutting concerns
•  To avoid tangling
•  To avoid Scattering
© Shakil Akhtar
Aspect Oriented Programming (AOP )
© Shakil Akhtar
Object A
Object C
Object B
method
method method
method
method
method
method
…
© Shakil Akhtar
Object A Object Bmet
hod
met
hod
advice
Object Oriented Programming
Target obj=obj B
Pointcut=method B
Aspect
Join point method =
invocation
AOP
Leading AOP Technologies
v AspectJ
•  Original AOP technology (first version in 1995)
•  Offers a full blown Aspect Oriented Programming
language
•  Uses byte code modification for aspect weaving
v Spring AOP
•  Java based AOP framework with AspectJ integration
•  Uses dynamic proxies for aspect weaving
•  Focuses on using AOP to solve enterprise problems
•  The Focus of this session
© Shakil Akhtar
Core AOP Concepts
v Join Point
•  A point in the execution point such as a method call or
field assignment or handling of an exception
v Pointcut
•  An expression that selects one or more join points
v Advice
•  Code to be executed at join point that has been selected
by a pointcut
v Aspect
•  A module that encapsulates pointcuts and advice
© Shakil Akhtar
Aspect
v  A modularization of a concern that cuts across
multiple classes
v Example Transaction management
v Two flavor
•  Code XML based
•  AspectJ Annotation style
© Shakil Akhtar
JoinPoint
v  A point during the execution of a program, such as
the execution of a method or the handling of an
exception
v This represents a point in your application where you can
plug-in AOP aspect
v A place in the application where an action will be taken
using Spring AOP framework
© Shakil Akhtar
Advice
v  Action taken by an aspect at a particular join point
v Example Transaction management
v This is actual piece of code that is invoked during
program execution
v Types of advice
•  Around
•  Before
•  After returning
•  After throwing
•  After (finally)
© Shakil Akhtar
Pointcut
v  A predicate that matches join points.Advice is
associated with a pointcut expression and runs at any
join point matched by the pointcut (for example, the
execution of a method with a certain name).
v A set of one or more joinpoints where an advice
should be executed
v Spring uses the AspectJ pointcut expression language
by default
© Shakil Akhtar
Introduction or inner-type
v  Declaring additional methods or fields on behalf of a
type
v Allows you to add new methods or attributes to
existing classes
v Example, you could use an introduction to make a
bean implement an IsModified interface, to simplify
caching
© Shakil Akhtar
Target Object
v  An object being advised by one or more aspects.
v This object will always be a proxied object
v Also referred as the advised object
© Shakil Akhtar
AOP Proxy
v  An object created by the AOP framework in order to
implement the aspect contracts (advise method
executions and so on).
v In Spring ,an AOP proxy will be a JDK dynamic proxy
or a CGLIB proxy
© Shakil Akhtar
Weaving
v  Linking aspects with other application types or
objects to create an advised object.
v This can be done at compile time (using the AspectJ
compiler, for example), load time, or at runtime
v Spring AOP, like other pure Java AOP frameworks,
performs weaving at runtime
© Shakil Akhtar
Considerations
v  Field interception is not implemented, although
support for field interception could be added using
AspectJ.The same for protected/private methods and
constructors.
© Shakil Akhtar
AOP Types
v Static AOP
•  In static AOP weaving process finds another step in the
build process for an application
•  AOP is achieved by modifying byte code
•  well –performing way of achieving the weaving process,
because the end result is just java byte code.
•  Recompilation requires for very join point addition
v Dynamic AOP
•  Dynamic AOP (spring AOP)
•  Weaving process is performed dynamically at runtime
•  Less performance than static AOP
© Shakil Akhtar
AOP Quick Start
v Consider the basic requirement
•  Log a message every time a property is going to change
v How can you use AOP to meet this?
© Shakil Akhtar
An Application Object whose
properties could change
public class SimpleCache implements Cache{
int cacheSize;
public void setCacheSize(int cacheSize) {
this.cacheSize = cacheSize;
}
...
}
© Shakil Akhtar
Implement the Aspect
@Aspect
public class PropertyChangeTracker {
private static final Log logger =
LogFactory.getLog(PropertyChangeTracker.class);
@Before("execution(void set*(*))")
public void trackChange(){
logger.info("property about to change");
}
}
© Shakil Akhtar
Best Practice Use Named Pointcuts
@Aspect
public class PropertyChangeTracker {
private static final Log logger =
LogFactory.getLog( PropertyChangeTracker.class);
@Before("setterMethod()")
public void trackChange(){
logger.info("property about to change");
}
@Pointcut("execution(void set*(*))")
public void setterMethod(){
}
}
© Shakil Akhtar
Configure the Aspect as a bean
<beans>
<aop:aspectj-autoproxy>
<aop:include name="propertyChangeTracker"/>
</aop:aspectj-autoproxy>
<bean id="propertyChangeTracker"
class="com.tr.spring.aop.PropertyChangeTracker" />
</beans>
Configures spring to apply the
@Aspect to your bean
aspect-config.xml
© Shakil Akhtar
Include the Aspect Configuration
<beans>
<import resource="aspect-config.xml"/>
<bean name="cache-A" class="com.tr.spring.aop.SimpleCache"/>
<bean name="cache-B" class="com.tr.spring.aop.SimpleCache"/>
<bean name="cache-C" class="com.tr.spring.aop.SimpleCache"/>
</beans>
application-config.xml
© Shakil Akhtar
Test the application
ApplicationContext appCtx = new
ClassPathXmlApplicationContext(APP_CTX_FILE_NAME);
Cache cache = (Cache) appCtx.getBean("cache-A");
cache.setCacheSize(2500);
INFO: property about to change
© Shakil Akhtar
How Aspects are applied
© Shakil Akhtar
How Aspects are applied
© Shakil Akhtar
Tracking property changes with Context
@Aspect
public class PropertyChangeTracker {
private static final Log logger =
LogFactory.getLog(PropertyChangeTracker.class);
@Before("setterMethod()")
public void trackChange( JoinPoint point){
String name = point.getSignature().getName();
Object newValue= point.getArgs()[0];
logger.info(name +"property about to change to " +newValue
+" on object" +point.getTarget());
}
@Pointcut("execution(void set*(*))")
public void setterMethod(){
}
}
Context about the
intercepted point
INFO: setCacheSizeproperty about to change to 2500 on object…
© Shakil Akhtar
Useful JoinPoint Context
v this
•  The currently executing object that has been
intercepted(a proxy in spring AOP)
v target
•  The target of the execution(typically your object)
v args
•  The method arguments passed to the join point
v signature
•  The method signature of the join point
© Shakil Akhtar
Defining Pointcuts
v With spring AOP you write pointcuts using AspectJ’s
pointcut expression language
•  For selecting where to apply advice
v Complete expression language reference available at
•  http://www.eclipse.org/aspectj
© Shakil Akhtar
Execution Expression Example
v execution(void send*(String))
•  Any method starting with send and takes a single string
parameter and has a void return type
v execution(* send(int,..))
•  Any method named send whose first parameter is an
int(the “..” signifies 0 or more parameters may follow
v execution(void example.MessageService+.send(*))
•  Any MessageService method named send that takes a
single parameter and returns void
© Shakil Akhtar
Execution Expression Example using
Annotations
v execution(@org.springframework.transaction.annotat
ion.Transactional void*(..))
•  Any method marked with the @Transactional annotation
v execution((@privacy.Sensitive*)*(..))
•  Any method that returns a value marked with the
@Sensitive annotation
© Shakil Akhtar
Pointcut Expression Example
v @Pointcut("execution(public * *(..))")
§  It will be applied on all the public methods.
v @Pointcut("execution(public Operation.*(..))")
§  It will be applied on all the public methods of Operation class
v @Pointcut("execution(* Operation.*(..))")
§  It will be applied on all the methods of Operation class
© Shakil Akhtar
Pointcut Expression Example
v @Pointcut("execution(public * *(..))")
§  It will be applied on all the public methods.
v @Pointcut("execution(public Operation.*(..))")
§  It will be applied on all the public methods of Operation class
© Shakil Akhtar
Advice Type: Before
© Shakil Akhtar
Advice Type: After Returning
© Shakil Akhtar
Advice Type: After Throwing
© Shakil Akhtar
Advice Type: After
© Shakil Akhtar
Advice Type: Around
© Shakil Akhtar
Advice Best Practices
v Use the simplest possible advice
•  Do not use @Around unless you must
© Shakil Akhtar
Alternative Spring AOP Syntax-XML
v Annotation syntax is java 5+ only
v XML syntax works on java 1.4
v Approach
•  Aspect logic defined java
•  Aspect configuration in XML
•  Easy to learn once annotation syntax is understood
© Shakil Akhtar
More Information
v Documentation
http://www.springsource.org
v Forum
http://forum.springsource.org/
v Spring Source Consulting
http://www.springsource.com/support/professional-
services
© Shakil Akhtar
© Shakil Akhtar
© Shakil Akhtar
shakilsoz17ster@gmail.com

Spring AOP

  • 1.
  • 2.
    Agenda v What problem doesAOP solve? v Core AOP concepts. v Quick Start. v Defining Pointcuts. v Implementing Advice. © Shakil Akhtar
  • 3.
    What are Cross-cuttingConcerns? v Generic functionality that’s needed in places in application. v Examples •  Logging •  Transaction Management •  Security •  Caching •  Error Handling •  Performance Monitoring •  Custom Business Rules © Shakil Akhtar
  • 4.
    An Example Requirement v Performa role based security check before every application method. A cross cutting concern requirement © Shakil Akhtar
  • 5.
    Implementing Cross-Cutting Concerns WithoutModularization v Failing to Modularize cross-cutting concerns leads to two things •  Code Tangling o  A couple of concerns •  Code scattering o  The same concern spread across modules © Shakil Akhtar
  • 6.
    Symptom #1: Tangling v Writetangling code © Shakil Akhtar
  • 7.
    Symptom #2: Scattering v Writescattering code © Shakil Akhtar
  • 8.
    System Evolution WithoutModularization © Shakil Akhtar
  • 9.
    How AOP Works v Implementyour mainline application logic •  Focusing on the core problem v Write aspects to implement your cross-cutting concerns •  Spring provides many aspects v Weave the aspects into your application •  Adding the cross cutting concern behavior’s to the right place © Shakil Akhtar
  • 10.
    Aspect Oriented Programming(AOP ) v Aspect Oriented Programming(AOP) enables modularization of cross-cutting concerns •  To avoid tangling •  To avoid Scattering © Shakil Akhtar
  • 11.
    Aspect Oriented Programming(AOP ) © Shakil Akhtar Object A Object C Object B method method method method method method method
  • 12.
    … © Shakil Akhtar ObjectA Object Bmet hod met hod advice Object Oriented Programming Target obj=obj B Pointcut=method B Aspect Join point method = invocation AOP
  • 13.
    Leading AOP Technologies v AspectJ • Original AOP technology (first version in 1995) •  Offers a full blown Aspect Oriented Programming language •  Uses byte code modification for aspect weaving v Spring AOP •  Java based AOP framework with AspectJ integration •  Uses dynamic proxies for aspect weaving •  Focuses on using AOP to solve enterprise problems •  The Focus of this session © Shakil Akhtar
  • 14.
    Core AOP Concepts v JoinPoint •  A point in the execution point such as a method call or field assignment or handling of an exception v Pointcut •  An expression that selects one or more join points v Advice •  Code to be executed at join point that has been selected by a pointcut v Aspect •  A module that encapsulates pointcuts and advice © Shakil Akhtar
  • 15.
    Aspect v  A modularizationof a concern that cuts across multiple classes v Example Transaction management v Two flavor •  Code XML based •  AspectJ Annotation style © Shakil Akhtar
  • 16.
    JoinPoint v  A pointduring the execution of a program, such as the execution of a method or the handling of an exception v This represents a point in your application where you can plug-in AOP aspect v A place in the application where an action will be taken using Spring AOP framework © Shakil Akhtar
  • 17.
    Advice v  Action takenby an aspect at a particular join point v Example Transaction management v This is actual piece of code that is invoked during program execution v Types of advice •  Around •  Before •  After returning •  After throwing •  After (finally) © Shakil Akhtar
  • 18.
    Pointcut v  A predicatethat matches join points.Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). v A set of one or more joinpoints where an advice should be executed v Spring uses the AspectJ pointcut expression language by default © Shakil Akhtar
  • 19.
    Introduction or inner-type v Declaring additional methods or fields on behalf of a type v Allows you to add new methods or attributes to existing classes v Example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching © Shakil Akhtar
  • 20.
    Target Object v  Anobject being advised by one or more aspects. v This object will always be a proxied object v Also referred as the advised object © Shakil Akhtar
  • 21.
    AOP Proxy v  Anobject created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). v In Spring ,an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy © Shakil Akhtar
  • 22.
    Weaving v  Linking aspectswith other application types or objects to create an advised object. v This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime v Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime © Shakil Akhtar
  • 23.
    Considerations v  Field interceptionis not implemented, although support for field interception could be added using AspectJ.The same for protected/private methods and constructors. © Shakil Akhtar
  • 24.
    AOP Types v Static AOP • In static AOP weaving process finds another step in the build process for an application •  AOP is achieved by modifying byte code •  well –performing way of achieving the weaving process, because the end result is just java byte code. •  Recompilation requires for very join point addition v Dynamic AOP •  Dynamic AOP (spring AOP) •  Weaving process is performed dynamically at runtime •  Less performance than static AOP © Shakil Akhtar
  • 25.
    AOP Quick Start v Considerthe basic requirement •  Log a message every time a property is going to change v How can you use AOP to meet this? © Shakil Akhtar
  • 26.
    An Application Objectwhose properties could change public class SimpleCache implements Cache{ int cacheSize; public void setCacheSize(int cacheSize) { this.cacheSize = cacheSize; } ... } © Shakil Akhtar
  • 27.
    Implement the Aspect @Aspect publicclass PropertyChangeTracker { private static final Log logger = LogFactory.getLog(PropertyChangeTracker.class); @Before("execution(void set*(*))") public void trackChange(){ logger.info("property about to change"); } } © Shakil Akhtar
  • 28.
    Best Practice UseNamed Pointcuts @Aspect public class PropertyChangeTracker { private static final Log logger = LogFactory.getLog( PropertyChangeTracker.class); @Before("setterMethod()") public void trackChange(){ logger.info("property about to change"); } @Pointcut("execution(void set*(*))") public void setterMethod(){ } } © Shakil Akhtar
  • 29.
    Configure the Aspectas a bean <beans> <aop:aspectj-autoproxy> <aop:include name="propertyChangeTracker"/> </aop:aspectj-autoproxy> <bean id="propertyChangeTracker" class="com.tr.spring.aop.PropertyChangeTracker" /> </beans> Configures spring to apply the @Aspect to your bean aspect-config.xml © Shakil Akhtar
  • 30.
    Include the AspectConfiguration <beans> <import resource="aspect-config.xml"/> <bean name="cache-A" class="com.tr.spring.aop.SimpleCache"/> <bean name="cache-B" class="com.tr.spring.aop.SimpleCache"/> <bean name="cache-C" class="com.tr.spring.aop.SimpleCache"/> </beans> application-config.xml © Shakil Akhtar
  • 31.
    Test the application ApplicationContextappCtx = new ClassPathXmlApplicationContext(APP_CTX_FILE_NAME); Cache cache = (Cache) appCtx.getBean("cache-A"); cache.setCacheSize(2500); INFO: property about to change © Shakil Akhtar
  • 32.
    How Aspects areapplied © Shakil Akhtar
  • 33.
    How Aspects areapplied © Shakil Akhtar
  • 34.
    Tracking property changeswith Context @Aspect public class PropertyChangeTracker { private static final Log logger = LogFactory.getLog(PropertyChangeTracker.class); @Before("setterMethod()") public void trackChange( JoinPoint point){ String name = point.getSignature().getName(); Object newValue= point.getArgs()[0]; logger.info(name +"property about to change to " +newValue +" on object" +point.getTarget()); } @Pointcut("execution(void set*(*))") public void setterMethod(){ } } Context about the intercepted point INFO: setCacheSizeproperty about to change to 2500 on object… © Shakil Akhtar
  • 35.
    Useful JoinPoint Context v this • The currently executing object that has been intercepted(a proxy in spring AOP) v target •  The target of the execution(typically your object) v args •  The method arguments passed to the join point v signature •  The method signature of the join point © Shakil Akhtar
  • 36.
    Defining Pointcuts v With springAOP you write pointcuts using AspectJ’s pointcut expression language •  For selecting where to apply advice v Complete expression language reference available at •  http://www.eclipse.org/aspectj © Shakil Akhtar
  • 37.
    Execution Expression Example v execution(voidsend*(String)) •  Any method starting with send and takes a single string parameter and has a void return type v execution(* send(int,..)) •  Any method named send whose first parameter is an int(the “..” signifies 0 or more parameters may follow v execution(void example.MessageService+.send(*)) •  Any MessageService method named send that takes a single parameter and returns void © Shakil Akhtar
  • 38.
    Execution Expression Exampleusing Annotations v execution(@org.springframework.transaction.annotat ion.Transactional void*(..)) •  Any method marked with the @Transactional annotation v execution((@privacy.Sensitive*)*(..)) •  Any method that returns a value marked with the @Sensitive annotation © Shakil Akhtar
  • 39.
    Pointcut Expression Example v @Pointcut("execution(public* *(..))") §  It will be applied on all the public methods. v @Pointcut("execution(public Operation.*(..))") §  It will be applied on all the public methods of Operation class v @Pointcut("execution(* Operation.*(..))") §  It will be applied on all the methods of Operation class © Shakil Akhtar
  • 40.
    Pointcut Expression Example v @Pointcut("execution(public* *(..))") §  It will be applied on all the public methods. v @Pointcut("execution(public Operation.*(..))") §  It will be applied on all the public methods of Operation class © Shakil Akhtar
  • 41.
  • 42.
    Advice Type: AfterReturning © Shakil Akhtar
  • 43.
    Advice Type: AfterThrowing © Shakil Akhtar
  • 44.
    Advice Type: After ©Shakil Akhtar
  • 45.
  • 46.
    Advice Best Practices v Usethe simplest possible advice •  Do not use @Around unless you must © Shakil Akhtar
  • 47.
    Alternative Spring AOPSyntax-XML v Annotation syntax is java 5+ only v XML syntax works on java 1.4 v Approach •  Aspect logic defined java •  Aspect configuration in XML •  Easy to learn once annotation syntax is understood © Shakil Akhtar
  • 48.
    More Information v Documentation http://www.springsource.org v Forum http://forum.springsource.org/ v Spring SourceConsulting http://www.springsource.com/support/professional- services © Shakil Akhtar
  • 49.
  • 50.