SlideShare une entreprise Scribd logo
1  sur  25
By: Rushi B Shah


What is AOP?



Why it is required?



AOP Terminology



AspectJ as an AOP framework



AspectJ Annotation Syntax



Different types of Advices and its Implementation


Concern is any use case/interest area present in
application



Core/Primary concern is the core business functionality



Cross-cutting/Secondary concern like authentication,
logging, exception handling



In OOP, we have tight coupling between core and crosscutting concerns



AOP introduces loose coupling between core and crosscutting concerns



AOP is nothing but modularization of concerns







AOP helps overcome system-level coding i.e.
logging, transaction mgmt, security mgmt,
caching, internationalization etc. by modularizing
cross-cutting concerns
AOP addresses each aspect separately thereby
minimizing coupling and duplication in code
It promotes code reuse
Developers can concentrate on one aspect at a
time
Make easier to add newer functionality's by
adding new aspects and weaving rules and
subsequently regenerating the final code.













Concern: A direct or indirect functionality to be addressed in the application
Aspect: It is a module that encapsulates a concern
Join Point: A point in the execution of a program like execution of a method or
handling of an exception
It denotes the “where” part
Advice: Action to be taken by the Aspect when a particular Join Point is reached
• It denotes the “what” part
Pointcut: It is a predicate that matches Join Point.
• It is an expression which defines which methods will be affected by the
Advice
• It denotes the “when” part
Target Object: The object being advised by one or more aspects
Weaving: Linking aspects to other application types or objects to create advised
objects
AOP Proxy: An object created by the AOP framework in order to implement the
aspect contracts (advise method executions and so on)
Advisor: An Advisor is like a small self-contained aspect that has a single piece of
advice.









Before advice: Advice that executes before a join

point, but which does not have the ability to prevent
execution flow proceeding to the join point (unless it
throws an exception).
After returning advice: Advice to be executed after a
join point completes normally: for example, if a
method returns without throwing an exception.
After throwing advice: Advice to be executed if a
method exits by throwing an exception.
After (finally) advice: Advice to be executed
regardless of the means by which a join point exits
(normal or exceptional return).
Around advice: Advice that surrounds a join point
such as a method invocation











Designator can have values like execution, within,
this.
Return type can be * to match any return type
Fully-qualified path means path with package
hierarchy (optional)
Method name can use * to match any name
Parameters can have values like “()” no param, “*”
any one parameter, “..” (Any no of parameters)
Designator({return-type} {fully-qualified path} {methodname} {parameters} {throws exception} )






Spring AOP interprets AspectJ annotations
at run-time by a library provided by AspectJ
framework.
Spring supports only method execution join
points for the beans in its IoC container.
So if you use join points beyond this scope
in Spring, it will give you
IllegalArgumentsException at runtime.
Type
Kinded

Dynamic

Scope

Syntax

Meaning
the method name
execution(* set*(*)) matches a method-execution join point, if
starts with "set" and there is exactly one argument of any type
and any one return type
this(Point)

within(com.company.*)

pointcut set() : execution(*
Composed set*(*) ) && this(Point) &&
within(com.company.*);

matches when the currently executing object is an instance of
class Point. Note that the unqualified name of a class can be
used via Java's normal type lookup.
matches any join point in any type in the com.company package.
The * is one form of the wildcards that can be used to match
many things with one signature.
matches a method-execution join point, if the method name
starts with "set" and any one return type and this is an instance
of type Point in the com.company package.


Using AspectJ Annotations

Using AspectJ XML Configuration(Schema
based approach)
In this scenario, an <aop:config> element can
contain pointcut, advisor, and aspect elements
(note: They must be declared in the same
order).


import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class BeforeExample {
@Before("execution(*com.xyz.myapp.dao.*.*(..))")
public void doAccessCheck() {
// method definition
}
}
<aop:aspectj-autoproxy />
<bean id="customerBo“
class="com.mkyong.customer.bo.impl.CustomerBoImpl"/>
<!--@Aspect -->
<bean id="logAspect"
class="com.mkyong.aspect.LoggingAspect" />
<aop:config>
<aop:aspect id="aspectLoggging" ref="logAspect" >
<!-- @Before -->
<aop:pointcut id="pointCutBefore“
expression="execution(*
com.mkyong.customer.bo.CustomerBo.addCustomer(..))" />
<aop:before method="logBefore" pointcutref="pointCutBefore" />
</aop:config>





import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
@Aspect
public class AfterReturningExample {



@AfterReturning(pointcut="com.xyz.myapp.SystemArchitecture
.dataAccessOperation()”, returning=“retVal”)



public void doAccessCheck() {



// method definition



}



}
<aop:aspectj-autoproxy />
<bean id="customerBo“
class="com.mkyong.customer.bo.impl.CustomerBoImpl"/>
<!--@Aspect -->
<bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" />
<aop:config>
<aop:aspect id="aspectLoggging" ref="logAspect" >
<!-- @AfterReturning -->
<aop:pointcut id="pointCutAfterReturning“
expression="execution(*
com.mkyong.customer.bo.CustomerBo.addCustomerReturnValu
e(..))" />
<aop:after-returning method="logAfterReturning" returning="result"
pointcut-ref="pointCutAfterReturning" />
</aop:config>
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;
@Aspect
public class AfterThrowingExample {
@AfterThrowing(pointcut="com.xyz.myapp.SystemArchi
tecture.dataAccessOperation()", throwing="ex")
public void doRecoveryActions(DataAccessException
ex) {
// method definition
}
}
<aop:aspectj-autoproxy />
<bean id="customerBo“
class="com.mkyong.customer.bo.impl.CustomerBoImpl"/>
<!--@Aspect -->
<bean id="logAspect" class="com.mkyong.aspect.LoggingAspect"
/>
<aop:config>
<aop:aspect id="aspectLoggging" ref="logAspect" >
<!-- @AfterThrowing -->
<aop:pointcut id="pointCutAfterThrowing“
expression="execution(*
com.mkyong.customer.bo.CustomerBo.addCustomerThrowExcepti
on(..))" />
<aop:after-throwing method="logAfterThrowing"
throwing="error"
pointcut-ref="pointCutAfterThrowing" />
</aop:config>
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;
@Aspect
public class AfterFinallyExample {
@After("com.xyz.myapp.SystemArchitecture.d
ataAccessOperation()")
public void doReleaseLock() {
// method definition
}
}
<aop:aspectj-autoproxy />
<bean id="customerBo“
class="com.mkyong.customer.bo.impl.CustomerBoImpl"/>
<!--@Aspect -->
<bean id="logAspect" class="com.mkyong.aspect.LoggingAspect"
/>
<aop:config>
<aop:aspect id="aspectLoggging" ref="logAspect" >
<!-- @After -->
<aop:pointcut id="pointCutAfter“ expression="execution(*
com.mkyong.customer.bo.CustomerBo.addCustomer(..))" />
<aop:after method="logAfter" pointcut-ref="pointCutAfter"
/>
</aop:aspect>
</aop:config>
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
@Aspect public class AroundExample {
@Around("com.xyz.myapp.SystemArchitecture.busi
nessService()")
public Object
doBasicProfiling(ProceedingJoinPoint pjp)
throws Throwable {
// just like before advice
Object retVal = pjp.proceed(); //original method call
// just like after returning advice
return retVal;

}
}
<aop:aspectj-autoproxy />
<bean id="customerBo“
class="com.mkyong.customer.bo.impl.CustomerBoImpl"/>
<!--@Aspect -->
<bean id="logAspect" class="com.mkyong.aspect.LoggingAspect"
/>
<aop:config>
<aop:aspect id="aspectLoggging" ref="logAspect" >
<aop:pointcut id="pointCutAround“
expression="execution(*
com.mkyong.customer.bo.CustomerBo.addCustomerAround
(..))" />
<aop:around method="logAround" pointcutref="pointCutAround" />
</aop:aspect>
</aop:config>
@Aspect
public class LoggingAspect {
@Before("execution(*com.mkyong.customer.bo.Cu
stomerBo.addCustomer(..))")
public void logBefore(JoinPoint joinPoint) {
//method definition }
}
@Aspect
public class OtherAspect {
@Before(LoggingAspect.logBefore())
//AspectClassName. methodname
public void otherMethod(JoinPoint joinpoint)
{ //method definition}
}










If you apply all the five types of advices on a
single method, then the execution order
irrespective of its
implementation(annotation-based or XML
configuration based) will be :
1) Before Advice
2) Before Proceed part of Around Advice
3) Actual method call execution
4) After Advice
5) After Returning Advice
6) After Proceed part of Around Advice












Spring AOP or full AspectJ?

If you only need to advise the execution of operations on Spring beans,
then Spring AOP is the right choice.
If you need to advise objects not managed by the Spring container (such
as domain objects typically), then you will need to use AspectJ. You will
also need to use AspectJ if you wish to advise join points other than
simple method executions (for example, field get or set join points, and
so on).
@AspectJ or XML for Spring AOP?
When using AOP as a tool to configure enterprise services then XML can
be a good choice because it is clearer from your configuration what
aspects are present in the system.
While using XML syntax, the aspect implementation is split across XML
Configuration file(containing pointcut expression) and backing bean
class(containing advice implementation).
But in @AspectJ syntax, both of these implementation remain in a single
aspect class and it is easy to combine two pointcut expression with it.
If the target object to be proxied implements at
least one interface then a JDK dynamic proxy will
be used. All of the interfaces implemented by the
target type will be proxied.
 If the target object does not implement any
interfaces then a CGLIB proxy will be created.
 If you want to force the use of CGLIB proxying
,there are some issues to consider:
i) final methods cannot be advised, as they
cannot be overridden.
ii) You will need the CGLIB 2 binaries on your
classpath, whereas
dynamic proxies are
available with the JDK. Spring will automatically
warn you when it needs CGLIB and the CGLIB
library classes are not found on the classpath.

Thank You

Contenu connexe

Tendances

SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 
Ad-hoc Runtime Object Structure Visualizations with MetaLinks
Ad-hoc Runtime Object Structure Visualizations with MetaLinks Ad-hoc Runtime Object Structure Visualizations with MetaLinks
Ad-hoc Runtime Object Structure Visualizations with MetaLinks ESUG
 
Dependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functionalDependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functionalMarian Wamsiedel
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignVictor Rentea
 
Exception Handling - Part 1
Exception Handling - Part 1 Exception Handling - Part 1
Exception Handling - Part 1 Hitesh-Java
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google MockICS
 
Pharo Optimising JIT Internals
Pharo Optimising JIT InternalsPharo Optimising JIT Internals
Pharo Optimising JIT InternalsESUG
 
Design functional solutions in Java, a practical example
Design functional solutions in Java, a practical exampleDesign functional solutions in Java, a practical example
Design functional solutions in Java, a practical exampleMarian Wamsiedel
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aopDror Helper
 
DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)Hendrik Ebbers
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesHarry Potter
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffJAX London
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsGanesh Samarthyam
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiRan Mizrahi
 

Tendances (19)

L07 Frameworks
L07 FrameworksL07 Frameworks
L07 Frameworks
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Ad-hoc Runtime Object Structure Visualizations with MetaLinks
Ad-hoc Runtime Object Structure Visualizations with MetaLinks Ad-hoc Runtime Object Structure Visualizations with MetaLinks
Ad-hoc Runtime Object Structure Visualizations with MetaLinks
 
Dependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functionalDependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functional
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable Design
 
Exception Handling - Part 1
Exception Handling - Part 1 Exception Handling - Part 1
Exception Handling - Part 1
 
L05 Frameworks
L05 FrameworksL05 Frameworks
L05 Frameworks
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
 
Pharo Optimising JIT Internals
Pharo Optimising JIT InternalsPharo Optimising JIT Internals
Pharo Optimising JIT Internals
 
Design functional solutions in Java, a practical example
Design functional solutions in Java, a practical exampleDesign functional solutions in Java, a practical example
Design functional solutions in Java, a practical example
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aop
 
DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
L09 Frameworks
L09 FrameworksL09 Frameworks
L09 Frameworks
 
Testing untestable code - DPC10
Testing untestable code - DPC10Testing untestable code - DPC10
Testing untestable code - DPC10
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 Exams
 
Frontend training
Frontend trainingFrontend training
Frontend training
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran Mizrahi
 

En vedette

Pointcut Rejuvenation: Recovering Pointcut Expressions in Evolving Aspect-Ori...
Pointcut Rejuvenation: Recovering Pointcut Expressions in Evolving Aspect-Ori...Pointcut Rejuvenation: Recovering Pointcut Expressions in Evolving Aspect-Ori...
Pointcut Rejuvenation: Recovering Pointcut Expressions in Evolving Aspect-Ori...Raffi Khatchadourian
 
Rejuvenate Pointcut: A Tool for Pointcut Expression Recovery in Evolving Aspe...
Rejuvenate Pointcut: A Tool for Pointcut Expression Recovery in Evolving Aspe...Rejuvenate Pointcut: A Tool for Pointcut Expression Recovery in Evolving Aspe...
Rejuvenate Pointcut: A Tool for Pointcut Expression Recovery in Evolving Aspe...Raffi Khatchadourian
 
Software rejuvenation
Software rejuvenationSoftware rejuvenation
Software rejuvenationRVCE2
 
Produce Cleaner Code with Aspect-Oriented Programming
Produce Cleaner Code with Aspect-Oriented ProgrammingProduce Cleaner Code with Aspect-Oriented Programming
Produce Cleaner Code with Aspect-Oriented ProgrammingPostSharp Technologies
 
Apache Solr lessons learned
Apache Solr lessons learnedApache Solr lessons learned
Apache Solr lessons learnedJeroen Rosenberg
 
Getting Started with Spring Framework
Getting Started with Spring FrameworkGetting Started with Spring Framework
Getting Started with Spring FrameworkEdureka!
 
Aspect-Oriented Programming for PHP
Aspect-Oriented Programming for PHPAspect-Oriented Programming for PHP
Aspect-Oriented Programming for PHPWilliam Candillon
 
Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingYan Cui
 
Java and services code lab spring boot and spring data using mongo db
Java and services code lab spring boot and spring data using mongo dbJava and services code lab spring boot and spring data using mongo db
Java and services code lab spring boot and spring data using mongo dbStaples
 
Aspect Oriented Software Development
Aspect Oriented Software DevelopmentAspect Oriented Software Development
Aspect Oriented Software DevelopmentJignesh Patel
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented ProgrammingAnumod Kumar
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 

En vedette (18)

Pointcut Rejuvenation: Recovering Pointcut Expressions in Evolving Aspect-Ori...
Pointcut Rejuvenation: Recovering Pointcut Expressions in Evolving Aspect-Ori...Pointcut Rejuvenation: Recovering Pointcut Expressions in Evolving Aspect-Ori...
Pointcut Rejuvenation: Recovering Pointcut Expressions in Evolving Aspect-Ori...
 
Rejuvenate Pointcut: A Tool for Pointcut Expression Recovery in Evolving Aspe...
Rejuvenate Pointcut: A Tool for Pointcut Expression Recovery in Evolving Aspe...Rejuvenate Pointcut: A Tool for Pointcut Expression Recovery in Evolving Aspe...
Rejuvenate Pointcut: A Tool for Pointcut Expression Recovery in Evolving Aspe...
 
Software rejuvenation
Software rejuvenationSoftware rejuvenation
Software rejuvenation
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Produce Cleaner Code with Aspect-Oriented Programming
Produce Cleaner Code with Aspect-Oriented ProgrammingProduce Cleaner Code with Aspect-Oriented Programming
Produce Cleaner Code with Aspect-Oriented Programming
 
Apache Solr lessons learned
Apache Solr lessons learnedApache Solr lessons learned
Apache Solr lessons learned
 
Getting Started with Spring Framework
Getting Started with Spring FrameworkGetting Started with Spring Framework
Getting Started with Spring Framework
 
Aspect-Oriented Programming for PHP
Aspect-Oriented Programming for PHPAspect-Oriented Programming for PHP
Aspect-Oriented Programming for PHP
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented Programming
 
Java and services code lab spring boot and spring data using mongo db
Java and services code lab spring boot and spring data using mongo dbJava and services code lab spring boot and spring data using mongo db
Java and services code lab spring boot and spring data using mongo db
 
Aspect Oriented Software Development
Aspect Oriented Software DevelopmentAspect Oriented Software Development
Aspect Oriented Software Development
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 

Similaire à Spring aop concepts

Similaire à Spring aop concepts (20)

Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOP
 
Session 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOPSession 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOP
 
Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented Programming
 
Spring aop
Spring aopSpring aop
Spring aop
 
Aspect-Oriented Programming
Aspect-Oriented ProgrammingAspect-Oriented Programming
Aspect-Oriented Programming
 
Spring aop
Spring aopSpring aop
Spring aop
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
AOP
AOPAOP
AOP
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
Spring aop
Spring aopSpring aop
Spring aop
 
Spring aop
Spring aopSpring aop
Spring aop
 
Aspect oriented programming with spring
Aspect oriented programming with springAspect oriented programming with spring
Aspect oriented programming with spring
 
Aspect-oriented programming in Perl
Aspect-oriented programming in PerlAspect-oriented programming in Perl
Aspect-oriented programming in Perl
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
 
45 aop-programming
45 aop-programming45 aop-programming
45 aop-programming
 
spring aop
spring aopspring aop
spring aop
 
Metrics by coda hale : to know your app’ health
Metrics by coda hale : to know your app’ healthMetrics by coda hale : to know your app’ health
Metrics by coda hale : to know your app’ health
 
Spring framework AOP
Spring framework  AOPSpring framework  AOP
Spring framework AOP
 
myslide1
myslide1myslide1
myslide1
 
myslide6
myslide6myslide6
myslide6
 

Dernier

The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 

Dernier (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 

Spring aop concepts

  • 1. By: Rushi B Shah
  • 2.  What is AOP?  Why it is required?  AOP Terminology  AspectJ as an AOP framework  AspectJ Annotation Syntax  Different types of Advices and its Implementation
  • 3.  Concern is any use case/interest area present in application  Core/Primary concern is the core business functionality  Cross-cutting/Secondary concern like authentication, logging, exception handling  In OOP, we have tight coupling between core and crosscutting concerns  AOP introduces loose coupling between core and crosscutting concerns  AOP is nothing but modularization of concerns
  • 4.      AOP helps overcome system-level coding i.e. logging, transaction mgmt, security mgmt, caching, internationalization etc. by modularizing cross-cutting concerns AOP addresses each aspect separately thereby minimizing coupling and duplication in code It promotes code reuse Developers can concentrate on one aspect at a time Make easier to add newer functionality's by adding new aspects and weaving rules and subsequently regenerating the final code.
  • 5.           Concern: A direct or indirect functionality to be addressed in the application Aspect: It is a module that encapsulates a concern Join Point: A point in the execution of a program like execution of a method or handling of an exception It denotes the “where” part Advice: Action to be taken by the Aspect when a particular Join Point is reached • It denotes the “what” part Pointcut: It is a predicate that matches Join Point. • It is an expression which defines which methods will be affected by the Advice • It denotes the “when” part Target Object: The object being advised by one or more aspects Weaving: Linking aspects to other application types or objects to create advised objects AOP Proxy: An object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on) Advisor: An Advisor is like a small self-contained aspect that has a single piece of advice.
  • 6.      Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception). After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception. After throwing advice: Advice to be executed if a method exits by throwing an exception. After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return). Around advice: Advice that surrounds a join point such as a method invocation
  • 7.       Designator can have values like execution, within, this. Return type can be * to match any return type Fully-qualified path means path with package hierarchy (optional) Method name can use * to match any name Parameters can have values like “()” no param, “*” any one parameter, “..” (Any no of parameters) Designator({return-type} {fully-qualified path} {methodname} {parameters} {throws exception} )
  • 8.    Spring AOP interprets AspectJ annotations at run-time by a library provided by AspectJ framework. Spring supports only method execution join points for the beans in its IoC container. So if you use join points beyond this scope in Spring, it will give you IllegalArgumentsException at runtime.
  • 9. Type Kinded Dynamic Scope Syntax Meaning the method name execution(* set*(*)) matches a method-execution join point, if starts with "set" and there is exactly one argument of any type and any one return type this(Point) within(com.company.*) pointcut set() : execution(* Composed set*(*) ) && this(Point) && within(com.company.*); matches when the currently executing object is an instance of class Point. Note that the unqualified name of a class can be used via Java's normal type lookup. matches any join point in any type in the com.company package. The * is one form of the wildcards that can be used to match many things with one signature. matches a method-execution join point, if the method name starts with "set" and any one return type and this is an instance of type Point in the com.company package.
  • 10.  Using AspectJ Annotations Using AspectJ XML Configuration(Schema based approach) In this scenario, an <aop:config> element can contain pointcut, advisor, and aspect elements (note: They must be declared in the same order). 
  • 11. import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class BeforeExample { @Before("execution(*com.xyz.myapp.dao.*.*(..))") public void doAccessCheck() { // method definition } }
  • 12. <aop:aspectj-autoproxy /> <bean id="customerBo“ class="com.mkyong.customer.bo.impl.CustomerBoImpl"/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <!-- @Before --> <aop:pointcut id="pointCutBefore“ expression="execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))" /> <aop:before method="logBefore" pointcutref="pointCutBefore" /> </aop:config>
  • 13.     import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.AfterReturning; @Aspect public class AfterReturningExample {  @AfterReturning(pointcut="com.xyz.myapp.SystemArchitecture .dataAccessOperation()”, returning=“retVal”)  public void doAccessCheck() {  // method definition  }  }
  • 14. <aop:aspectj-autoproxy /> <bean id="customerBo“ class="com.mkyong.customer.bo.impl.CustomerBoImpl"/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <!-- @AfterReturning --> <aop:pointcut id="pointCutAfterReturning“ expression="execution(* com.mkyong.customer.bo.CustomerBo.addCustomerReturnValu e(..))" /> <aop:after-returning method="logAfterReturning" returning="result" pointcut-ref="pointCutAfterReturning" /> </aop:config>
  • 15. import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.AfterThrowing; @Aspect public class AfterThrowingExample { @AfterThrowing(pointcut="com.xyz.myapp.SystemArchi tecture.dataAccessOperation()", throwing="ex") public void doRecoveryActions(DataAccessException ex) { // method definition } }
  • 16. <aop:aspectj-autoproxy /> <bean id="customerBo“ class="com.mkyong.customer.bo.impl.CustomerBoImpl"/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <!-- @AfterThrowing --> <aop:pointcut id="pointCutAfterThrowing“ expression="execution(* com.mkyong.customer.bo.CustomerBo.addCustomerThrowExcepti on(..))" /> <aop:after-throwing method="logAfterThrowing" throwing="error" pointcut-ref="pointCutAfterThrowing" /> </aop:config>
  • 17. import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.After; @Aspect public class AfterFinallyExample { @After("com.xyz.myapp.SystemArchitecture.d ataAccessOperation()") public void doReleaseLock() { // method definition } }
  • 18. <aop:aspectj-autoproxy /> <bean id="customerBo“ class="com.mkyong.customer.bo.impl.CustomerBoImpl"/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <!-- @After --> <aop:pointcut id="pointCutAfter“ expression="execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))" /> <aop:after method="logAfter" pointcut-ref="pointCutAfter" /> </aop:aspect> </aop:config>
  • 19. import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.ProceedingJoinPoint; @Aspect public class AroundExample { @Around("com.xyz.myapp.SystemArchitecture.busi nessService()") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { // just like before advice Object retVal = pjp.proceed(); //original method call // just like after returning advice return retVal; } }
  • 20. <aop:aspectj-autoproxy /> <bean id="customerBo“ class="com.mkyong.customer.bo.impl.CustomerBoImpl"/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <aop:pointcut id="pointCutAround“ expression="execution(* com.mkyong.customer.bo.CustomerBo.addCustomerAround (..))" /> <aop:around method="logAround" pointcutref="pointCutAround" /> </aop:aspect> </aop:config>
  • 21. @Aspect public class LoggingAspect { @Before("execution(*com.mkyong.customer.bo.Cu stomerBo.addCustomer(..))") public void logBefore(JoinPoint joinPoint) { //method definition } } @Aspect public class OtherAspect { @Before(LoggingAspect.logBefore()) //AspectClassName. methodname public void otherMethod(JoinPoint joinpoint) { //method definition} }
  • 22.        If you apply all the five types of advices on a single method, then the execution order irrespective of its implementation(annotation-based or XML configuration based) will be : 1) Before Advice 2) Before Proceed part of Around Advice 3) Actual method call execution 4) After Advice 5) After Returning Advice 6) After Proceed part of Around Advice
  • 23.        Spring AOP or full AspectJ? If you only need to advise the execution of operations on Spring beans, then Spring AOP is the right choice. If you need to advise objects not managed by the Spring container (such as domain objects typically), then you will need to use AspectJ. You will also need to use AspectJ if you wish to advise join points other than simple method executions (for example, field get or set join points, and so on). @AspectJ or XML for Spring AOP? When using AOP as a tool to configure enterprise services then XML can be a good choice because it is clearer from your configuration what aspects are present in the system. While using XML syntax, the aspect implementation is split across XML Configuration file(containing pointcut expression) and backing bean class(containing advice implementation). But in @AspectJ syntax, both of these implementation remain in a single aspect class and it is easy to combine two pointcut expression with it.
  • 24. If the target object to be proxied implements at least one interface then a JDK dynamic proxy will be used. All of the interfaces implemented by the target type will be proxied.  If the target object does not implement any interfaces then a CGLIB proxy will be created.  If you want to force the use of CGLIB proxying ,there are some issues to consider: i) final methods cannot be advised, as they cannot be overridden. ii) You will need the CGLIB 2 binaries on your classpath, whereas dynamic proxies are available with the JDK. Spring will automatically warn you when it needs CGLIB and the CGLIB library classes are not found on the classpath. 