• Save
Spring AOP Introduction
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
2,601
On Slideshare
2,501
From Embeds
100
Number of Embeds
2

Actions

Shares
Downloads
1
Comments
0
Likes
1

Embeds 100

http://www.btrofimoff.com 92
http://fromboris.blogspot.com 8

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

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

Transcript

  • 1. SPRING AOPINTRODUCTION Boris Trofimov @ Sigma Ukraine@b0ris_1
  • 2. One exampleAOP introductionSpring AOP basicsExamples and Use CasesBest practicesWeaknessesSigma Ukraine2AGENDA
  • 3. Convert exceptions crossing layers, respecting layer rules (UIalerts, shaping exceptions etc.)Sigma Ukraine3ONE EXAMPLE
  • 4. Exception handling – with handlers, typical approachSigma Ukraine4ONE EXAMPLE
  • 5. Exception handling – with handlers, typical approachSigma Ukraine5ONE EXAMPLE
  • 6. There is cross-cutting functionality that does not belong tospecific module or object. Often it should be supported by manyobjects 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 oneplace. However pure major paradigms (OOP, procedural,component-driven) cannot encapsulate and express this logicefficiently.Functional Scala-like approach might help through closures-decorators, however it has own weaknesses.Sigma Ukraine6THE PROBLEM
  • 7. Crosscutting concern is decomposed into several notions:Aspect – crosscutting implementation, regular bean withmethod (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 callsWeaving – linking advice with other target objects to create anadvised object (compile or creation stage)Sigma Ukraine7AOP BASIC CONCEPTS
  • 8. Sigma Ukraine8HELLO, IT’S SPRING AOP
  • 9. Spring AOP is implemented in pure JavaAspect is an ordinary bean with own injection rulesWeaving with Spring AOP is performed during instantiationtime: injection/creation or directApplicationContext.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 AnnotationsSigma Ukraine9SPRING AOP
  • 10. Add Spring references into maven pom file:Sigma Ukraine10STEPS 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 Ukraine11STEPS 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 1Object ret = call.proceed();// do something, part 2return ret;}}<bean id="AspectBeanReference"class="com.xyz.services.aspect.ServiceAspect"/>
  • 12. Register Advice and Pointcut:Sigma Ukraine12STEPS 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 expresspointcuts. Pointcuts might define classes as well as interfacesExamplesexecution(* *.*(..)) – expresses aspect call after execution of anypublic method;execution(* *.set*(..)) – expresses aspect call after execution of anymethod which name starts with “set”;execution(* com.xyz.service.AccountService.*(..)) – expressesaspect call after execution of any method for classcom.xyz.service.AccountService;execution(* com.xyz.service.*.*(..)) – expresses aspect call for anymethod of objects from package service;annotation(com.xyz.service.MyAnnotation) - expresses aspectcall for method, whose object support annotation.Sigma Ukraine13A FEW WORDS ON POINTCUTS
  • 14. Sigma Ukraine14ADVICESBEFORE ADVICEimport org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;@Aspectpublic class BeforeExample {@Before("execution(* com.xyz.myapp.dao.*.*(..))")public void doAccessCheck() {// ...}}
  • 15. Sigma Ukraine15ADVICESAFTER RETURNINGimport org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.AfterReturning;@Aspectpublic class AfterReturningExample {@AfterReturning(pointcut="execution(* com.xyz.myapp.dao.*.*(..))",returning="retVal")public void doAccessCheck(Object retVal) {// ...}}
  • 16. Sigma Ukraine16ADVICESAFTER THROWING ADVICEimport org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.AfterThrowing;@Aspectpublic class AfterThrowingExample {@AfterThrowing(pointcut="execution(* com.xyz.myapp.dao.*.*(..))",throwing="ex")public void doRecoveryActions(Exception ex) {// ...}}
  • 17. Sigma Ukraine17ADVICESAFTER (FINALLY) ADVICEimport org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.After;@Aspectpublic class AfterFinallyExample {@After("execution(* com.xyz.myapp.dao.*.*(..))")public void doReleaseLock() {// ...}}
  • 18. Sigma Ukraine18ADVICESAROUND ADVICEimport org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.ProceedingJoinPoint;@Aspectpublic class AroundExample {@Around("execution(* com.xyz.myapp.dao.*.*(..))")public Object doBasicProfiling(ProceedingJoinPoint pjp)throws Throwable {// start stopwatchObject retVal = pjp.proceed();// stop stopwatchreturn retVal;}}
  • 19. Task is to convert exceptions crossing layers.Define pointcut covering edge components for specific layer.Define aspectSigma Ukraine19TRANSPARENT EXCEPTION HANDLINGimport org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.ProceedingJoinPoint;@Aspectpublic 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 @Transactionalannotations. Usually it is top edge of application service layer.Take into account aspect order – transactions should havebigger value.Sigma Ukraine20RE-LAUNCHING BROKEN TRANSACTIONS@Aspectpublic 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. AuditPerform authentication rulesHidden LoggingMeasure method executionAligning to transaction resultSigma Ukraine21MORE APPLICATIONS
  • 22. Any pointcut should be expressed by singleexpression.Any pointcut should be “linearized”.Do not invent a wheel: use customized SpringAOP technics like exception handling for SpringMVC or Spring declarative transactions.One cross-cutting concern should be matchedto one aspect implementation.In case of layered architecture and XMLapproach treat all aspects from one layer inone place [like board room].AOP might be integrated into legacy project, itshould have clear architecture and DI (is itpossible?!).Sigma Ukraine22BEST PRACTICES
  • 23. AOP is not silver bullet. Do not use iteverywhere. Excessive AOP usage makesapplication even more difficult tounderstand than without it.Take into account overhead (creation&execution time ). In many cases it mightmatter. Use AspectJ bytecode weavingapproach.Be aware of Spring’s proxy approach.Spring AOP is based on Spring DI.Sigma Ukraine23AOP CONCERNS
  • 24. Sigma Ukraine24AOP OVERHEAD5000 (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,97206Calling weaved object with empty aspect (Series 2) 55,736513 225,285998 1897,525577 20110,53607Calling weaved object with math aspect (Series 3) 65,556692 343,241082 3141,977656 32587,01187050001000015000200002500030000350005000 (in ms) 50000 (in ms) 500.000 (in ms) 5.000.000 (in ms)Series1Series2Series3Experiment details:AMD Athlon X4, 3 GHz
  • 25. Sigma Ukraine25AOP BENCHMARKSAWBench(relative %)aspectwerkz aspectj spring dynaopbefore, args()target()1 x 1 x 35.5 x 39 xaround x 2, args()target()1 x 0.6 x 5.4 x 5.6 xbefore, rtti infoaccess1 x 1 x 5.5 x 6.7 xafter returning 1 x 1 x 28.5 x 31.5 xbefore + after 1 x 1 x 22.2 x 17.2 xbefore, args()primitives1 x 1 x 35 x 37.5 xbefore, args()objects1 x 2 x 65 x 69 xaround, rtti infoaccess1 x 0.7 x 3.5 x 4.8 xaround, staticinfo access1 x 0.3 x 3 x 4.1 xSource: http://docs.codehaus.org/display/AW/AOP+Benchmark
  • 26. Thank you for your attention!