SlideShare a Scribd company logo
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

More Related Content

PPTX
Spring AOP Introduction
b0ris_1
 
PPTX
Spring AOP in Nutshell
Onkar Deshpande
 
PPTX
Spring aop concepts
RushiBShah
 
PPT
Spring AOP
AnushaNaidu
 
PDF
AOP
Joshua Yoon
 
PPTX
Spring framework part 2
Skillwise Group
 
PDF
Dart for Java Developers
Yakov Fain
 
PDF
Advice weaving in AspectJ
Sander Mak (@Sander_Mak)
 
Spring AOP Introduction
b0ris_1
 
Spring AOP in Nutshell
Onkar Deshpande
 
Spring aop concepts
RushiBShah
 
Spring AOP
AnushaNaidu
 
Spring framework part 2
Skillwise Group
 
Dart for Java Developers
Yakov Fain
 
Advice weaving in AspectJ
Sander Mak (@Sander_Mak)
 

What's hot (20)

ODP
Aspect-Oriented Programming
Andrey Bratukhin
 
PDF
DataFX 8 (JavaOne 2014)
Hendrik Ebbers
 
PPTX
Introduction to aop
Dror Helper
 
PDF
Ad-hoc Runtime Object Structure Visualizations with MetaLinks
ESUG
 
PDF
Pharo Optimising JIT Internals
ESUG
 
PPTX
Apex Testing and Best Practices
Jitendra Zaa
 
PDF
Sling Models Using Sightly and JSP by Deepak Khetawat
AEM HUB
 
PPTX
What's New in Java 8
javafxpert
 
PDF
JavaFX8 TestFX - CDI
Sven Ruppert
 
PDF
Dependency injection in Java, from naive to functional
Marian Wamsiedel
 
PDF
Android MvRx Framework 介紹
Kros Huang
 
PDF
vJUG - The JavaFX Ecosystem
Andres Almiray
 
ODP
Unit Testing and Coverage for AngularJS
Knoldus Inc.
 
PPTX
AEM and Sling
Lo Ki
 
PDF
Design functional solutions in Java, a practical example
Marian Wamsiedel
 
PDF
Living With Legacy Code
Rowan Merewood
 
PPT
Adam Peller Interoperable Ajax Tools And Mashups
Ajax Experience 2009
 
PDF
Benefits of OSGi in Practise
David Bosschaert
 
PPTX
Mastering the Sling Rewriter
Justin Edelson
 
PPTX
Zend Studio Tips and Tricks
Roy Ganor
 
Aspect-Oriented Programming
Andrey Bratukhin
 
DataFX 8 (JavaOne 2014)
Hendrik Ebbers
 
Introduction to aop
Dror Helper
 
Ad-hoc Runtime Object Structure Visualizations with MetaLinks
ESUG
 
Pharo Optimising JIT Internals
ESUG
 
Apex Testing and Best Practices
Jitendra Zaa
 
Sling Models Using Sightly and JSP by Deepak Khetawat
AEM HUB
 
What's New in Java 8
javafxpert
 
JavaFX8 TestFX - CDI
Sven Ruppert
 
Dependency injection in Java, from naive to functional
Marian Wamsiedel
 
Android MvRx Framework 介紹
Kros Huang
 
vJUG - The JavaFX Ecosystem
Andres Almiray
 
Unit Testing and Coverage for AngularJS
Knoldus Inc.
 
AEM and Sling
Lo Ki
 
Design functional solutions in Java, a practical example
Marian Wamsiedel
 
Living With Legacy Code
Rowan Merewood
 
Adam Peller Interoperable Ajax Tools And Mashups
Ajax Experience 2009
 
Benefits of OSGi in Practise
David Bosschaert
 
Mastering the Sling Rewriter
Justin Edelson
 
Zend Studio Tips and Tricks
Roy Ganor
 
Ad

Viewers also liked (20)

KEY
Spring AOP
Jeroen Rosenberg
 
PPTX
Introduction to Aspect Oriented Programming
Yan Cui
 
PPTX
Produce Cleaner Code with Aspect-Oriented Programming
PostSharp Technologies
 
PDF
Apache Solr lessons learned
Jeroen Rosenberg
 
ODP
Aspect-Oriented Programming for PHP
William Candillon
 
PPT
Aspect Oriented Software Development
Jignesh Patel
 
PPT
Aspect Oriented Programming
Anumod Kumar
 
PDF
Spring Framework - AOP
Dzmitry Naskou
 
PPTX
Algebra 2 powerpoint
roohal51
 
PDF
Hospice letter
nm118486
 
PPT
1200 j lipman
SMACC Conference
 
PDF
Know Your Supplier - Rubber & Tyre Machinery World May 2016 Special
Rubber & Tyre Machinery World
 
PDF
Planejamento pms
Alessandro Leboreiro de Souza
 
PDF
How to unlock alcatel one touch fierce 7024w by unlock code
rscooldesire
 
PPT
新希望.
sft
 
PPTX
I AM HR: FIVE STRATEGIC WAYS TO BREAK STEREOTYPES AND RECLAIM HR
Laurie Ruettimann
 
PDF
Swedish Match Tobacco Export Portfolio
Emiliano Rocha
 
PDF
IBM Big Data References
Rob Thomas
 
PDF
Rapport Doing Business 2015
Franck Dasilva
 
PPT
Auraplus ciuziniai
Seo Paslaugos
 
Spring AOP
Jeroen Rosenberg
 
Introduction to Aspect Oriented Programming
Yan Cui
 
Produce Cleaner Code with Aspect-Oriented Programming
PostSharp Technologies
 
Apache Solr lessons learned
Jeroen Rosenberg
 
Aspect-Oriented Programming for PHP
William Candillon
 
Aspect Oriented Software Development
Jignesh Patel
 
Aspect Oriented Programming
Anumod Kumar
 
Spring Framework - AOP
Dzmitry Naskou
 
Algebra 2 powerpoint
roohal51
 
Hospice letter
nm118486
 
1200 j lipman
SMACC Conference
 
Know Your Supplier - Rubber & Tyre Machinery World May 2016 Special
Rubber & Tyre Machinery World
 
How to unlock alcatel one touch fierce 7024w by unlock code
rscooldesire
 
新希望.
sft
 
I AM HR: FIVE STRATEGIC WAYS TO BREAK STEREOTYPES AND RECLAIM HR
Laurie Ruettimann
 
Swedish Match Tobacco Export Portfolio
Emiliano Rocha
 
IBM Big Data References
Rob Thomas
 
Rapport Doing Business 2015
Franck Dasilva
 
Auraplus ciuziniai
Seo Paslaugos
 
Ad

Similar to Spring AOP (20)

PDF
Spring aop
Hamid Ghorbani
 
PPT
Spring AOP
Lhouceine OUHAMZA
 
PPTX
spring aop
Kalyani Patil
 
PPT
Spring aop
UMA MAHESWARI
 
PPTX
Spring aop
sanskriti agarwal
 
PDF
Spring framework aop
Taemon Piya-Lumyong
 
PPTX
spring aop.pptxfgfdgfdgfdgfdgfdgvbvcbvbcvbdf
zmulani8
 
PPTX
Spring AOP
Radhakrishna Mutthoju
 
PPTX
spring aop.pptx aspt oreinted programmin
zmulani8
 
PPTX
Spring framework AOP
Anuj Singh Rajput
 
PDF
AOP (Aspect-Oriented Programming) spring boot
PLAYAFIFI
 
PPT
Spring AOP @ DevClub.eu
arsenikum
 
PPTX
Spring aop
Harshit Choudhary
 
PPT
Aop spring
chamilavt
 
PPTX
Introduction to Aspect Oriented Programming
Amir Kost
 
PPTX
Aspect Oriented Programming
Rajesh Ganesan
 
PPTX
Session 45 - Spring - Part 3 - AOP
PawanMM
 
PPSX
Spring - Part 3 - AOP
Hitesh-Java
 
PDF
Aspect oriented programming with spring
Sreenivas Kappala
 
Spring aop
Hamid Ghorbani
 
Spring AOP
Lhouceine OUHAMZA
 
spring aop
Kalyani Patil
 
Spring aop
UMA MAHESWARI
 
Spring aop
sanskriti agarwal
 
Spring framework aop
Taemon Piya-Lumyong
 
spring aop.pptxfgfdgfdgfdgfdgfdgvbvcbvbcvbdf
zmulani8
 
spring aop.pptx aspt oreinted programmin
zmulani8
 
Spring framework AOP
Anuj Singh Rajput
 
AOP (Aspect-Oriented Programming) spring boot
PLAYAFIFI
 
Spring AOP @ DevClub.eu
arsenikum
 
Spring aop
Harshit Choudhary
 
Aop spring
chamilavt
 
Introduction to Aspect Oriented Programming
Amir Kost
 
Aspect Oriented Programming
Rajesh Ganesan
 
Session 45 - Spring - Part 3 - AOP
PawanMM
 
Spring - Part 3 - AOP
Hitesh-Java
 
Aspect oriented programming with spring
Sreenivas Kappala
 

Recently uploaded (20)

PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
PDF
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ
 
PDF
Make GenAI investments go further with the Dell AI Factory - Infographic
Principled Technologies
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PPTX
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
This slide provides an overview Technology
mineshkharadi333
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Doc9.....................................
SofiaCollazos
 
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ
 
Make GenAI investments go further with the Dell AI Factory - Infographic
Principled Technologies
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 

Spring AOP

  • 2. Agenda v What problem does AOP solve? v Core AOP concepts. v Quick Start. v Defining Pointcuts. v Implementing Advice. © Shakil Akhtar
  • 3. 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
  • 4. An Example Requirement v Perform a role based security check before every application method. A cross cutting concern requirement © Shakil Akhtar
  • 5. 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
  • 6. Symptom #1: Tangling v Write tangling code © Shakil Akhtar
  • 7. Symptom #2: Scattering v Write scattering code © Shakil Akhtar
  • 8. System Evolution Without Modularization © Shakil Akhtar
  • 9. 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
  • 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 Object A 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 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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
  • 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  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
  • 21. 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
  • 22. 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
  • 23. 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
  • 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 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
  • 26. An Application Object whose 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 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
  • 28. 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
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. How Aspects are applied © Shakil Akhtar
  • 33. How Aspects are applied © Shakil Akhtar
  • 34. 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
  • 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 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
  • 37. 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
  • 38. 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
  • 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. Advice Type: Before © Shakil Akhtar
  • 42. Advice Type: After Returning © Shakil Akhtar
  • 43. Advice Type: After Throwing © Shakil Akhtar
  • 44. Advice Type: After © Shakil Akhtar
  • 45. Advice Type: Around © Shakil Akhtar
  • 46. Advice Best Practices v Use the simplest possible advice •  Do not use @Around unless you must © Shakil Akhtar
  • 47. 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