SlideShare ist ein Scribd-Unternehmen logo
1 von 26
SPRING AOP
INTRODUCTION Boris Trofimov @ Sigma Ukraine
@b0ris_1
One example
AOP introduction
Spring AOP basics
Examples and Use Cases
Best practices
Weaknesses
Sigma Ukraine2
AGENDA
Convert exceptions crossing layers, respecting layer rules (UI
alerts, shaping exceptions etc.)
Sigma Ukraine3
ONE EXAMPLE
Exception handling – with handlers, typical approach
Sigma Ukraine4
ONE EXAMPLE
Exception handling – with handlers, typical approach
Sigma Ukraine5
ONE EXAMPLE
There is cross-cutting functionality that does not belong to
specific module or object. Often it should be supported by many
objects from different places (logging, exception handling, audit,
auth, …). Spreading it throughout the project is not a option.
It would be good to handle specific cross-cutting concern in one
place. However pure major paradigms (OOP, procedural,
component-driven) cannot encapsulate and express this logic
efficiently.
Functional Scala-like approach might help through closures-
decorators, however it has own weaknesses.
Sigma Ukraine6
THE PROBLEM
Crosscutting concern is decomposed into several notions:
Aspect – crosscutting implementation, regular bean with
method (examples: exception handling)
Join point – usually it represents a method execution.
Pointcut – expression that matches join point.
Advice – join-point and aspect integration, types "around,"
"before" and "after“.
Target Object – object to be advised by one or more aspects.
AOP proxy (or Advised Object ) – proxy with advice calls
Weaving – linking advice with other target objects to create an
advised object (compile or creation stage)
Sigma Ukraine7
AOP BASIC CONCEPTS
Sigma Ukraine8
HELLO, IT’S SPRING AOP
Spring AOP is implemented in pure Java
Aspect is an ordinary bean with own injection rules
Weaving with Spring AOP is performed during instantiation
time: injection/creation or direct
ApplicationContext.getBean (through Spring DI)
Only Proxy Approach (JDK dynamic proxies or CGLIB)
Spring AOP is based on AspectJ framework interfaces.
Two ways of aspect integration: XML and Annotations
Sigma Ukraine9
SPRING AOP
Add Spring references into maven pom file:
Sigma Ukraine10
STEPS TO ADD ASPECT – 1 (3)
( FOR AROUND ADVICE)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.12</version>
</dependency>
Create bean-aspect into project, register it as Spring bean:
Sigma Ukraine11
STEPS TO ADD ASPECT – 1 (3)
( FOR AROUND ADVICE)
package com.xyz.services.aspect;
public class ServiceAspect {
public Object run(ProceedingJoinPoint call) throws Throwable {
// do something, part 1
Object ret = call.proceed();
// do something, part 2
return ret;
}
}
<bean id="AspectBeanReference"
class="com.xyz.services.aspect.ServiceAspect"/>
Register Advice and Pointcut:
Sigma Ukraine12
STEPS TO ADD ASPECT – 2 (3)
( FOR AROUND ADVICE)
<aop:config>
<aop:aspect id="MyAspect" ref="AspectBeanReference" order="250">
<aop:pointcut id="MyNameOfPointcut"
expression=
"execution(* com.xyz.services.impl.*ServiceImpl.*(..))"/>
<aop:around pointcut-ref="MyNameOfPointcut" method="run"/>
</aop:aspect>
</aop:config>
<!-- <aop:aspectj-autoproxy/> -->
 Spring AOP uses AspectJ subset language to express
pointcuts.
 Pointcuts might define classes as well as interfaces
Examples
execution(* *.*(..)) – expresses aspect call after execution of any
public method;
execution(* *.set*(..)) – expresses aspect call after execution of any
method which name starts with “set”;
execution(* com.xyz.service.AccountService.*(..)) – expresses
aspect call after execution of any method for class
com.xyz.service.AccountService;
execution(* com.xyz.service.*.*(..)) – expresses aspect call for any
method of objects from package service;
annotation(com.xyz.service.MyAnnotation) - expresses aspect
call for method, whose object support annotation.
Sigma Ukraine13
A FEW WORDS ON POINTCUTS
Sigma Ukraine14
ADVICES
BEFORE ADVICE
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() {
// ...
}
}
Sigma Ukraine15
ADVICES
AFTER RETURNING
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
@Aspect
public class AfterReturningExample {
@AfterReturning(
pointcut="execution(* com.xyz.myapp.dao.*.*(..))",
returning="retVal")
public void doAccessCheck(Object retVal) {
// ...
}
}
Sigma Ukraine16
ADVICES
AFTER THROWING ADVICE
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;
@Aspect
public class AfterThrowingExample {
@AfterThrowing(
pointcut="execution(* com.xyz.myapp.dao.*.*(..))",
throwing="ex")
public void doRecoveryActions(Exception ex) {
// ...
}
}
Sigma Ukraine17
ADVICES
AFTER (FINALLY) ADVICE
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;
@Aspect
public class AfterFinallyExample {
@After("execution(* com.xyz.myapp.dao.*.*(..))")
public void doReleaseLock() {
// ...
}
}
Sigma Ukraine18
ADVICES
AROUND ADVICE
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
@Aspect
public class AroundExample {
@Around("execution(* com.xyz.myapp.dao.*.*(..))")
public Object doBasicProfiling(ProceedingJoinPoint pjp)
throws Throwable {
// start stopwatch
Object retVal = pjp.proceed();
// stop stopwatch
return retVal;
}
}
Task is to convert exceptions crossing layers.
Define pointcut covering edge components for specific layer.
Define aspect
Sigma Ukraine19
TRANSPARENT EXCEPTION HANDLING
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
@Aspect
public class ExceptionTranslatorExample {
@Around("execution(* com.xyz.domain.*Repository.*(..)) ")
public Object doBasicProfiling(ProceedingJoinPoint pjp)
throws Throwable {
try{
Object retVal = pjp.proceed();
return retVal;
}
catch (SQLException ex){
throw new DomainException(ex);
}
}
}
Define pointcut to cover beans with @Transactional
annotations. Usually it is top edge of application service layer.
Take into account aspect order – transactions should have
bigger value.
Sigma Ukraine20
RE-LAUNCHING BROKEN TRANSACTIONS
@Aspect
public class ExceptionTranslatorExample {
@Around("execution(* com.xyz.applicationServices.*Service.*(..)) ")
public Object doBasicProfiling(ProceedingJoinPoint pjp)
throws Throwable {
int counter = 0;
do{
try{
return pjp.proceed();
}
catch (DeadLockException ex)
if((++counter)==2)
throw ex;
}
while(true);
}
}
Audit
Perform authentication rules
Hidden Logging
Measure method execution
Aligning to transaction result
Sigma Ukraine21
MORE APPLICATIONS
Any pointcut should be expressed by single
expression.
Any pointcut should be “linearized”.
Do not invent a wheel: use customized Spring
AOP technics like exception handling for Spring
MVC or Spring declarative transactions.
One cross-cutting concern should be matched
to one aspect implementation.
In case of layered architecture and XML
approach treat all aspects from one layer in
one place [like board room].
AOP might be integrated into legacy project, it
should have clear architecture and DI (is it
possible?!).
Sigma Ukraine22
BEST PRACTICES
AOP is not silver bullet. Do not use it
everywhere. Excessive AOP usage makes
application even more difficult to
understand than without it.
Take into account overhead (creation&
execution time ). In many cases it might
matter. Use AspectJ bytecode weaving
approach.
Be aware of Spring’s proxy approach.
Spring AOP is based on Spring DI.
Sigma Ukraine23
AOP CONCERNS
Sigma Ukraine24
AOP OVERHEAD
5000 (in ms) 50000 (in ms) 500.000 (in ms) 5.000.000 (in ms)
Calling pure math object (Series 1) 46,008952 131,986317 1194,716932 13661,97206
Calling weaved object with empty aspect (Series 2) 55,736513 225,285998 1897,525577 20110,53607
Calling weaved object with math aspect (Series 3) 65,556692 343,241082 3141,977656 32587,01187
0
5000
10000
15000
20000
25000
30000
35000
5000 (in ms) 50000 (in ms) 500.000 (in ms) 5.000.000 (in ms)
Series1
Series2
Series3
Experiment details:
AMD Athlon X4, 3 GHz
Sigma Ukraine25
AOP BENCHMARKS
AWBench
(relative %)
aspectwerkz aspectj spring dynaop
before, args()
target()
1 x 1 x 35.5 x 39 x
around x 2, args()
target()
1 x 0.6 x 5.4 x 5.6 x
before, rtti info
access
1 x 1 x 5.5 x 6.7 x
after returning 1 x 1 x 28.5 x 31.5 x
before + after 1 x 1 x 22.2 x 17.2 x
before, args()
primitives
1 x 1 x 35 x 37.5 x
before, args()
objects
1 x 2 x 65 x 69 x
around, rtti info
access
1 x 0.7 x 3.5 x 4.8 x
around, static
info access
1 x 0.3 x 3 x 4.1 x
Source: http://docs.codehaus.org/display/AW/AOP+Benchmark
Thank you for your attention!

Weitere ähnliche Inhalte

Was ist angesagt?

Extending Spark With Java Agent (handout)
Extending Spark With Java Agent (handout)Extending Spark With Java Agent (handout)
Extending Spark With Java Agent (handout)
Jaroslav Bachorik
 

Was ist angesagt? (20)

JavaFX8 TestFX - CDI
JavaFX8   TestFX - CDIJavaFX8   TestFX - CDI
JavaFX8 TestFX - CDI
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in Java
 
Android MvRx Framework 介紹
Android MvRx Framework 介紹Android MvRx Framework 介紹
Android MvRx Framework 介紹
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
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
 
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
 
AOP in Python API design
AOP in Python API designAOP in Python API design
AOP in Python API design
 
Benefits of OSGi in Practise
Benefits of OSGi in PractiseBenefits of OSGi in Practise
Benefits of OSGi in Practise
 
What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8
 
AEM and Sling
AEM and SlingAEM and Sling
AEM and Sling
 
The Web on OSGi: Here's How
The Web on OSGi: Here's HowThe Web on OSGi: Here's How
The Web on OSGi: Here's How
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
 
JavaOne - The JavaFX Community and Ecosystem
JavaOne - The JavaFX Community and EcosystemJavaOne - The JavaFX Community and Ecosystem
JavaOne - The JavaFX Community and Ecosystem
 
Alteryx SDK
Alteryx SDKAlteryx SDK
Alteryx SDK
 
Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training
 
Extending Spark With Java Agent (handout)
Extending Spark With Java Agent (handout)Extending Spark With Java Agent (handout)
Extending Spark With Java Agent (handout)
 
A First Date With Scala
A First Date With ScalaA First Date With Scala
A First Date With Scala
 
Vladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable ModuleVladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable Module
 

Andere mochten auch

Aspect oriented programming_with_spring
Aspect oriented programming_with_springAspect oriented programming_with_spring
Aspect oriented programming_with_spring
Guo Albert
 

Andere mochten auch (14)

Aspect oriented programming_with_spring
Aspect oriented programming_with_springAspect oriented programming_with_spring
Aspect oriented programming_with_spring
 
Audience counting at Scale
Audience counting at ScaleAudience counting at Scale
Audience counting at Scale
 
Scalding big ADta
Scalding big ADtaScalding big ADta
Scalding big ADta
 
Bending Spark towards enterprise needs
Bending Spark towards enterprise needsBending Spark towards enterprise needs
Bending Spark towards enterprise needs
 
MongoDB Distilled
MongoDB DistilledMongoDB Distilled
MongoDB Distilled
 
Scalding Big (Ad)ta
Scalding Big (Ad)taScalding Big (Ad)ta
Scalding Big (Ad)ta
 
Faster persistent data structures through hashing
Faster persistent data structures through hashingFaster persistent data structures through hashing
Faster persistent data structures through hashing
 
Continuous DB migration based on carbon5 framework
Continuous DB migration based on carbon5 frameworkContinuous DB migration based on carbon5 framework
Continuous DB migration based on carbon5 framework
 
So various polymorphism in Scala
So various polymorphism in ScalaSo various polymorphism in Scala
So various polymorphism in Scala
 
Clustering Java applications with Terracotta and Hazelcast
Clustering Java applications with Terracotta and HazelcastClustering Java applications with Terracotta and Hazelcast
Clustering Java applications with Terracotta and Hazelcast
 
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
 
Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented Programming
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 

Ähnlich wie Spring AOP Introduction

SiriusCon2016 - Modelling Spacecraft On-board Software with Sirius
SiriusCon2016 - Modelling Spacecraft On-board Software with SiriusSiriusCon2016 - Modelling Spacecraft On-board Software with Sirius
SiriusCon2016 - Modelling Spacecraft On-board Software with Sirius
Obeo
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2
Niti Chotkaew
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
Julien Lecomte
 

Ähnlich wie Spring AOP Introduction (20)

SiriusCon2016 - Modelling Spacecraft On-board Software with Sirius
SiriusCon2016 - Modelling Spacecraft On-board Software with SiriusSiriusCon2016 - Modelling Spacecraft On-board Software with Sirius
SiriusCon2016 - Modelling Spacecraft On-board Software with Sirius
 
AOP on Android
AOP on AndroidAOP on Android
AOP on Android
 
Spring framework part 2
Spring framework  part 2Spring framework  part 2
Spring framework part 2
 
AngularJS - Overcoming performance issues. Limits.
AngularJS - Overcoming performance issues. Limits.AngularJS - Overcoming performance issues. Limits.
AngularJS - Overcoming performance issues. Limits.
 
Dragos Rusu - Angular JS - Overcoming Performance Issues - CodeCamp-10-may-2014
Dragos Rusu  - Angular JS - Overcoming Performance Issues - CodeCamp-10-may-2014Dragos Rusu  - Angular JS - Overcoming Performance Issues - CodeCamp-10-may-2014
Dragos Rusu - Angular JS - Overcoming Performance Issues - CodeCamp-10-may-2014
 
Session 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOPSession 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOP
 
Aspect Oriented Programming and MVC with Spring Framework
Aspect Oriented Programming and MVC with Spring FrameworkAspect Oriented Programming and MVC with Spring Framework
Aspect Oriented Programming and MVC with Spring Framework
 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOP
 
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)
 
Static Analysis of Context Leaks in Android Applications
Static Analysis of Context Leaks in Android ApplicationsStatic Analysis of Context Leaks in Android Applications
Static Analysis of Context Leaks in Android Applications
 
[MOPCON2018] Effectively shrink ProGuard rules for reducing APK size
[MOPCON2018] Effectively shrink ProGuard rules for reducing APK size[MOPCON2018] Effectively shrink ProGuard rules for reducing APK size
[MOPCON2018] Effectively shrink ProGuard rules for reducing APK size
 
WebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webWebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open web
 
Jdk Tools For Performance Diagnostics
Jdk Tools For Performance DiagnosticsJdk Tools For Performance Diagnostics
Jdk Tools For Performance Diagnostics
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
A Deep Dive into Query Execution Engine of Spark SQL
A Deep Dive into Query Execution Engine of Spark SQLA Deep Dive into Query Execution Engine of Spark SQL
A Deep Dive into Query Execution Engine of Spark SQL
 
Spring aop concepts
Spring aop conceptsSpring aop concepts
Spring aop concepts
 
Untangling spring week7
Untangling spring week7Untangling spring week7
Untangling spring week7
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
 

Mehr von b0ris_1

Mehr von b0ris_1 (8)

Learning from nature or human body as a source on inspiration for software en...
Learning from nature or human body as a source on inspiration for software en...Learning from nature or human body as a source on inspiration for software en...
Learning from nature or human body as a source on inspiration for software en...
 
Devoxx 2022
Devoxx 2022Devoxx 2022
Devoxx 2022
 
IT Arena-2021
IT Arena-2021IT Arena-2021
IT Arena-2021
 
New accelerators in Big Data - Upsolver
New accelerators in Big Data - UpsolverNew accelerators in Big Data - Upsolver
New accelerators in Big Data - Upsolver
 
Learning from nature [slides from Software Architecture meetup]
Learning from nature [slides from Software Architecture meetup]Learning from nature [slides from Software Architecture meetup]
Learning from nature [slides from Software Architecture meetup]
 
Cowboy dating with big data TechDays at Lohika-2020
Cowboy dating with big data TechDays at Lohika-2020Cowboy dating with big data TechDays at Lohika-2020
Cowboy dating with big data TechDays at Lohika-2020
 
Cowboy dating with big data
Cowboy dating with big data Cowboy dating with big data
Cowboy dating with big data
 
Ultimate journey towards realtime data platform with 2.5M events per sec
Ultimate journey towards realtime data platform with 2.5M events per secUltimate journey towards realtime data platform with 2.5M events per sec
Ultimate journey towards realtime data platform with 2.5M events per sec
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Spring AOP Introduction

  • 1. SPRING AOP INTRODUCTION Boris Trofimov @ Sigma Ukraine @b0ris_1
  • 2. One example AOP introduction Spring AOP basics Examples and Use Cases Best practices Weaknesses Sigma Ukraine2 AGENDA
  • 3. Convert exceptions crossing layers, respecting layer rules (UI alerts, shaping exceptions etc.) Sigma Ukraine3 ONE EXAMPLE
  • 4. Exception handling – with handlers, typical approach Sigma Ukraine4 ONE EXAMPLE
  • 5. Exception handling – with handlers, typical approach Sigma Ukraine5 ONE EXAMPLE
  • 6. There is cross-cutting functionality that does not belong to specific module or object. Often it should be supported by many objects from different places (logging, exception handling, audit, auth, …). Spreading it throughout the project is not a option. It would be good to handle specific cross-cutting concern in one place. However pure major paradigms (OOP, procedural, component-driven) cannot encapsulate and express this logic efficiently. Functional Scala-like approach might help through closures- decorators, however it has own weaknesses. Sigma Ukraine6 THE PROBLEM
  • 7. Crosscutting concern is decomposed into several notions: Aspect – crosscutting implementation, regular bean with method (examples: exception handling) Join point – usually it represents a method execution. Pointcut – expression that matches join point. Advice – join-point and aspect integration, types "around," "before" and "after“. Target Object – object to be advised by one or more aspects. AOP proxy (or Advised Object ) – proxy with advice calls Weaving – linking advice with other target objects to create an advised object (compile or creation stage) Sigma Ukraine7 AOP BASIC CONCEPTS
  • 9. Spring AOP is implemented in pure Java Aspect is an ordinary bean with own injection rules Weaving with Spring AOP is performed during instantiation time: injection/creation or direct ApplicationContext.getBean (through Spring DI) Only Proxy Approach (JDK dynamic proxies or CGLIB) Spring AOP is based on AspectJ framework interfaces. Two ways of aspect integration: XML and Annotations Sigma Ukraine9 SPRING AOP
  • 10. Add Spring references into maven pom file: Sigma Ukraine10 STEPS TO ADD ASPECT – 1 (3) ( FOR AROUND ADVICE) <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>3.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.7.2</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.12</version> </dependency>
  • 11. Create bean-aspect into project, register it as Spring bean: Sigma Ukraine11 STEPS TO ADD ASPECT – 1 (3) ( FOR AROUND ADVICE) package com.xyz.services.aspect; public class ServiceAspect { public Object run(ProceedingJoinPoint call) throws Throwable { // do something, part 1 Object ret = call.proceed(); // do something, part 2 return ret; } } <bean id="AspectBeanReference" class="com.xyz.services.aspect.ServiceAspect"/>
  • 12. Register Advice and Pointcut: Sigma Ukraine12 STEPS TO ADD ASPECT – 2 (3) ( FOR AROUND ADVICE) <aop:config> <aop:aspect id="MyAspect" ref="AspectBeanReference" order="250"> <aop:pointcut id="MyNameOfPointcut" expression= "execution(* com.xyz.services.impl.*ServiceImpl.*(..))"/> <aop:around pointcut-ref="MyNameOfPointcut" method="run"/> </aop:aspect> </aop:config> <!-- <aop:aspectj-autoproxy/> -->
  • 13.  Spring AOP uses AspectJ subset language to express pointcuts.  Pointcuts might define classes as well as interfaces Examples execution(* *.*(..)) – expresses aspect call after execution of any public method; execution(* *.set*(..)) – expresses aspect call after execution of any method which name starts with “set”; execution(* com.xyz.service.AccountService.*(..)) – expresses aspect call after execution of any method for class com.xyz.service.AccountService; execution(* com.xyz.service.*.*(..)) – expresses aspect call for any method of objects from package service; annotation(com.xyz.service.MyAnnotation) - expresses aspect call for method, whose object support annotation. Sigma Ukraine13 A FEW WORDS ON POINTCUTS
  • 14. Sigma Ukraine14 ADVICES BEFORE ADVICE 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() { // ... } }
  • 15. Sigma Ukraine15 ADVICES AFTER RETURNING import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.AfterReturning; @Aspect public class AfterReturningExample { @AfterReturning( pointcut="execution(* com.xyz.myapp.dao.*.*(..))", returning="retVal") public void doAccessCheck(Object retVal) { // ... } }
  • 16. Sigma Ukraine16 ADVICES AFTER THROWING ADVICE import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.AfterThrowing; @Aspect public class AfterThrowingExample { @AfterThrowing( pointcut="execution(* com.xyz.myapp.dao.*.*(..))", throwing="ex") public void doRecoveryActions(Exception ex) { // ... } }
  • 17. Sigma Ukraine17 ADVICES AFTER (FINALLY) ADVICE import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.After; @Aspect public class AfterFinallyExample { @After("execution(* com.xyz.myapp.dao.*.*(..))") public void doReleaseLock() { // ... } }
  • 18. Sigma Ukraine18 ADVICES AROUND ADVICE import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.ProceedingJoinPoint; @Aspect public class AroundExample { @Around("execution(* com.xyz.myapp.dao.*.*(..))") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { // start stopwatch Object retVal = pjp.proceed(); // stop stopwatch return retVal; } }
  • 19. Task is to convert exceptions crossing layers. Define pointcut covering edge components for specific layer. Define aspect Sigma Ukraine19 TRANSPARENT EXCEPTION HANDLING import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.ProceedingJoinPoint; @Aspect public class ExceptionTranslatorExample { @Around("execution(* com.xyz.domain.*Repository.*(..)) ") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { try{ Object retVal = pjp.proceed(); return retVal; } catch (SQLException ex){ throw new DomainException(ex); } } }
  • 20. Define pointcut to cover beans with @Transactional annotations. Usually it is top edge of application service layer. Take into account aspect order – transactions should have bigger value. Sigma Ukraine20 RE-LAUNCHING BROKEN TRANSACTIONS @Aspect public class ExceptionTranslatorExample { @Around("execution(* com.xyz.applicationServices.*Service.*(..)) ") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { int counter = 0; do{ try{ return pjp.proceed(); } catch (DeadLockException ex) if((++counter)==2) throw ex; } while(true); } }
  • 21. Audit Perform authentication rules Hidden Logging Measure method execution Aligning to transaction result Sigma Ukraine21 MORE APPLICATIONS
  • 22. Any pointcut should be expressed by single expression. Any pointcut should be “linearized”. Do not invent a wheel: use customized Spring AOP technics like exception handling for Spring MVC or Spring declarative transactions. One cross-cutting concern should be matched to one aspect implementation. In case of layered architecture and XML approach treat all aspects from one layer in one place [like board room]. AOP might be integrated into legacy project, it should have clear architecture and DI (is it possible?!). Sigma Ukraine22 BEST PRACTICES
  • 23. AOP is not silver bullet. Do not use it everywhere. Excessive AOP usage makes application even more difficult to understand than without it. Take into account overhead (creation& execution time ). In many cases it might matter. Use AspectJ bytecode weaving approach. Be aware of Spring’s proxy approach. Spring AOP is based on Spring DI. Sigma Ukraine23 AOP CONCERNS
  • 24. Sigma Ukraine24 AOP OVERHEAD 5000 (in ms) 50000 (in ms) 500.000 (in ms) 5.000.000 (in ms) Calling pure math object (Series 1) 46,008952 131,986317 1194,716932 13661,97206 Calling weaved object with empty aspect (Series 2) 55,736513 225,285998 1897,525577 20110,53607 Calling weaved object with math aspect (Series 3) 65,556692 343,241082 3141,977656 32587,01187 0 5000 10000 15000 20000 25000 30000 35000 5000 (in ms) 50000 (in ms) 500.000 (in ms) 5.000.000 (in ms) Series1 Series2 Series3 Experiment details: AMD Athlon X4, 3 GHz
  • 25. Sigma Ukraine25 AOP BENCHMARKS AWBench (relative %) aspectwerkz aspectj spring dynaop before, args() target() 1 x 1 x 35.5 x 39 x around x 2, args() target() 1 x 0.6 x 5.4 x 5.6 x before, rtti info access 1 x 1 x 5.5 x 6.7 x after returning 1 x 1 x 28.5 x 31.5 x before + after 1 x 1 x 22.2 x 17.2 x before, args() primitives 1 x 1 x 35 x 37.5 x before, args() objects 1 x 2 x 65 x 69 x around, rtti info access 1 x 0.7 x 3.5 x 4.8 x around, static info access 1 x 0.3 x 3 x 4.1 x Source: http://docs.codehaus.org/display/AW/AOP+Benchmark
  • 26. Thank you for your attention!

Hinweis der Redaktion

  1. Рассмотрим классическиКаждый слой, каждая группа компонент, будь то bounded context или некоторая подсистема могут быть свои правила по конвертации excerptinonsи трансляции их в более удобное представлениеPresentaation layer…Многие из вас замечали что тот же Hibernate ....Вообще говоря боксинг исключительных ситуаций это нормальная практика.
  2. Многие из вас сталкивались с уродливыми многочсленными try/catch и ваыполеннием однотипной логики раскиданной по коду
  3. В идеале ыло бы здорово вообще убратьtry/catch и вынести их за пределыМогу сказат ьчто на нашем проекте у нас проактически нету try.catchexceptions. Все вендили между слоями хорошо изолированы конвертационыне правила хорошо инкапсулированы в вентили. И это позводяет хорошо контролировать сложность.И наша система не протекает.
  4. Прошлая задача вводит нам такое понятие как cross-cuttingИтак АОП появляется так где есть cross-cutting functionality
  5. I might say that spring declarative transactions already use AOP approach.
  6. После этого все вызовы методов всех сервисов данного пакета будут декорироваться нашим аспектом.
  7. Spring AOP предлагает вашему вниманию гораздо больший диапозон выражений, упомянутые выражения встречаются чаще всего , и они выходят за рамки этого доклада
  8. Allegory АОП в отличие ест ьчто-то типа портясающей припраы к вашему салату, которая сделает ваш салат неабываемым, но если переборщите то придется выбрасывать.It is possible to prepare doklad “Как я завалил проект используюя Spring AOP”.Если в контролируете аспекты то очекнь вероятно что у вас с первормансом все ок, но если пострадал перфоманкс, это признак того что вы потеряли контроль над аспектами. И аспекты контролируют вас
  9. Могу от себя добавить что у нас на проекте используется порядка 7 разных аспектов. Мы переключилина AspectJ декларативные транзакции и получили выигрыв в производительности 15-20 %.