Your SlideShare is downloading. ×
0
Spring Framework - AOP                SPRING FRAMEWORK 3.0Dmitry Noskov   Aspect Oriented Programming with Spring
Aspect Oriented Programming          Spring Framework - AOP   Dmitry Noskov
What is AOP?   is a programming paradigm   extends OOP   enables modularization of crosscutting concerns   is second h...
A simple service methodpublic Order getOrder(BigDecimal orderId) {    return (Order) factory.openSession()                ...
Add permissions checkpublic Order getOrder(BigDecimal orderId) {    if (hasOrderPermission(orderId)) {        return (Orde...
Add transaction managementpublic Order getOrder(BigDecimal orderId) {    if (hasOrderPermission(orderId)) {        Order o...
Add cachepublic Order getOrder(BigDecimal orderId) {    if (hasOrderPermission(orderId)) {        Order order = (Order)cac...
A similar problem at enterprise level                 Spring Framework - AOP   Dmitry Noskov
What does AOP solve?LoggingValidationCachingSecurityTransactionsMonitoringError HandlingEtc…                 Spring Framew...
AOP concepts   aspect   advice   pointcut   join point                 Spring Framework - AOP   Dmitry Noskov
AOP and OOPAOP                                            OOP1.   Aspect – code unit that                   1.   Class – c...
AOP concepts(2)   introduction   target object   AOP proxy   weaving     compile time     load time     runtime    ...
Spring AOP   implemented in pure java   no need for a special compilation process   supports only method execution join...
@AspectJ           Spring Framework - AOP   Dmitry Noskov
Declaring aspect@Aspectpublic class EmptyAspect {}<!--<context:annotation-config />--><aop:aspectj-autoproxy proxy-target-...
Declaring pointcut            Spring Framework - AOP   Dmitry Noskov
Pointcut designators   code based     execution     within     target     this     args     bean                  S...
Pointcut designators(2)   annotation based     @annotation     @within     @target     @args                       Sp...
Format of an execution expressionexecution(  modifiers-pattern  returning-type-pattern  declaring-type-pattern  name-patte...
Simple pointcut expressions@Aspectpublic class ItemStatusTracker {    @Pointcut("execution(* approve(..))")    public void...
Execution examplesany public methodexecution(public * * (..))"any method with a name beginning with "get"execution(* get*(...
Declaring advice           Spring Framework - AOP   Dmitry Noskov
Advice   associated with a pointcut expression     a simple reference to a named pointcut     a pointcut expression dec...
Before advice@Aspectpublic class BankAspect {    @Pointcut("execution(public * * (..))")    public void anyPublicMethod() ...
After returning advice@Aspectpublic class BankAspect {    @AfterReturning(          pointcut="execution(* get*(..))",     ...
After throwing advice@Aspectpublic class BankAspect {    @AfterThrowing(          pointcut = "execution(* bank..*ServiceIm...
After finally advice@Aspectpublic class BankAspect {    @Pointcut("execution(public * * (..))")    public void anyPublicMe...
Around advice@Aspectpublic class BankCacheAspect {    @Around("@annotation(bank.Cached)")    public Object aroundCache(Pro...
Aspect and advice ordering   order of advice in the same aspect     before     around     after finally     after ret...
XML based AOP         Spring Framework - AOP   Dmitry Noskov
Declaring an aspect<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       ...
How it all works            Spring Framework - AOP   Dmitry Noskov
Bean in Spring containerStandard OOP implementation            Implementation with AOP                              Spring...
AOP proxiesInvoke directly            Invoke via proxy                  Spring Framework - AOP   Dmitry Noskov
How it really works               Spring Framework - AOP   Dmitry Noskov
Introductions            Spring Framework - AOP   Dmitry Noskov
Introduction behaviors to bean@Aspectpublic class CalculatorIntroduction {    @DeclareParents(          value = "calculato...
Introduction states to bean@Aspectpublic class BankServiceIntroductionAspect {    @DeclareParents(          value="bank.Ba...
Spring AOP vs AspectJSpring AOP                           AspectJ   no need for a special               need AspectJ com...
@AspectJ vs XML@AspectJ                           XML   has more opportunities,           can be used with any    such a...
Links   Useful links       Wiki: Aspect-oriented programming        http://en.wikipedia.org/wiki/Aspect-oriented_program...
Books        Spring Framework - AOP   Dmitry Noskov
Questions            Spring Framework - AOP   Dmitry Noskov
The end             http://www.linkedin.com/in/noskovd      http://www.slideshare.net/analizator/presentations
Upcoming SlideShare
Loading in...5
×

Spring Framework - AOP

5,521

Published on

Aspect oriented programming with Spring Framework.
AspectJ support.

Published in: Technology, Education

Transcript of "Spring Framework - AOP"

  1. 1. Spring Framework - AOP SPRING FRAMEWORK 3.0Dmitry Noskov Aspect Oriented Programming with Spring
  2. 2. Aspect Oriented Programming Spring Framework - AOP Dmitry Noskov
  3. 3. What is AOP? is a programming paradigm extends OOP enables modularization of crosscutting concerns is second heart of Spring Framework Spring Framework - AOP Dmitry Noskov
  4. 4. A simple service methodpublic Order getOrder(BigDecimal orderId) { return (Order) factory.openSession() .get(Order.class, orderId);} Spring Framework - AOP Dmitry Noskov
  5. 5. Add permissions checkpublic Order getOrder(BigDecimal orderId) { if (hasOrderPermission(orderId)) { return (Order) factory.openSession() .get(Order.class, orderId); } else { throw new SecurityException("Access Denied"); }} Spring Framework - AOP Dmitry Noskov
  6. 6. Add transaction managementpublic Order getOrder(BigDecimal orderId) { if (hasOrderPermission(orderId)) { Order order; Session session = factory.openSession(); Transaction tx = session.beginTransaction(); try { order = (Order) session.get(Order.class, orderId); tx.commit(); } catch (RuntimeException e) {if (tx!=null) {tx.rollback();} } finally {session.close();} return order; } else { throw new SecurityException("Access Denied");}} Spring Framework - AOP Dmitry Noskov
  7. 7. Add cachepublic Order getOrder(BigDecimal orderId) { if (hasOrderPermission(orderId)) { Order order = (Order)cache.get(orderId); if (order==null) { Session session = factory.openSession(); Transaction tx = session.beginTransaction(); try { order = (Order) session.get(Order.class, orderId); tx.commit(); cache.put(orderId, order); } catch (RuntimeException e) {if (tx!=null) {tx.rollback();} } finally {session.close();} } return order; } else { throw new SecurityException("Access Denied");}} Spring Framework - AOP Dmitry Noskov
  8. 8. A similar problem at enterprise level Spring Framework - AOP Dmitry Noskov
  9. 9. What does AOP solve?LoggingValidationCachingSecurityTransactionsMonitoringError HandlingEtc… Spring Framework - AOP Dmitry Noskov
  10. 10. AOP concepts aspect advice pointcut join point Spring Framework - AOP Dmitry Noskov
  11. 11. AOP and OOPAOP OOP1. Aspect – code unit that 1. Class – code unit that encapsulates pointcuts, advice, encapsulates methods and and attributes attributes2. Pointcut – define the set of 2. Method signature – define the entry points (triggers) in which entry points for the execution of advice is executed method bodies3. Advice – implementation of 3. Method bodies –implementation cross cutting concern of the business logic concerns4. Weaver – construct code 4. Compiler – convert source code (source or object) with advice to object code Spring Framework - AOP Dmitry Noskov
  12. 12. AOP concepts(2) introduction target object AOP proxy weaving  compile time  load time  runtime Spring Framework - AOP Dmitry Noskov
  13. 13. Spring AOP implemented in pure java no need for a special compilation process supports only method execution join points only runtime weaving is available AOP proxy  JDK dynamic proxy  CGLIB proxy configuration  @AspectJ annotation-style  Spring XML configuration-style Spring Framework - AOP Dmitry Noskov
  14. 14. @AspectJ Spring Framework - AOP Dmitry Noskov
  15. 15. Declaring aspect@Aspectpublic class EmptyAspect {}<!--<context:annotation-config />--><aop:aspectj-autoproxy proxy-target-class="false | true"/><beanclass="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"></bean><bean class="example.EmptyAspect"/> Spring Framework - AOP Dmitry Noskov
  16. 16. Declaring pointcut Spring Framework - AOP Dmitry Noskov
  17. 17. Pointcut designators code based  execution  within  target  this  args  bean Spring Framework - AOP Dmitry Noskov
  18. 18. Pointcut designators(2) annotation based  @annotation  @within  @target  @args Spring Framework - AOP Dmitry Noskov
  19. 19. Format of an execution expressionexecution( modifiers-pattern returning-type-pattern declaring-type-pattern name-pattern(param-pattern) throws-pattern) Spring Framework - AOP Dmitry Noskov
  20. 20. Simple pointcut expressions@Aspectpublic class ItemStatusTracker { @Pointcut("execution(* approve(..))") public void ifApprove() {} @Pointcut("execution(* reject(..))") public void ifReject() {} @Pointcut("ifApprove() || ifReject()") public void ifStateChange() {}} Spring Framework - AOP Dmitry Noskov
  21. 21. Execution examplesany public methodexecution(public * * (..))"any method with a name beginning with "get"execution(* get*(..))any method defined by the appropriate interfaceexecution(* bank.BankService.*(..))any method defined in the appropriate packageexecution(* com.epam.pmc.service.*.*(..))other exampleshttp://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-pointcuts-examples Spring Framework - AOP Dmitry Noskov
  22. 22. Declaring advice Spring Framework - AOP Dmitry Noskov
  23. 23. Advice associated with a pointcut expression  a simple reference to a named pointcut  a pointcut expression declared in place runs  before  after returning  after throwing  after (finally)  around Spring Framework - AOP Dmitry Noskov
  24. 24. Before advice@Aspectpublic class BankAspect { @Pointcut("execution(public * * (..))") public void anyPublicMethod() {} @Before("anyPublicMethod()") public void logBefore(JoinPoint joinPoint) { //to do something }} Spring Framework - AOP Dmitry Noskov
  25. 25. After returning advice@Aspectpublic class BankAspect { @AfterReturning( pointcut="execution(* get*(..))", returning="retVal") public void logAfter(JoinPoint joinPoint, Object retVal) { //to do something }} Spring Framework - AOP Dmitry Noskov
  26. 26. After throwing advice@Aspectpublic class BankAspect { @AfterThrowing( pointcut = "execution(* bank..*ServiceImpl.add*(..))", throwing = "exception") public void afterThrowing(Exception exception) { //to do something }} Spring Framework - AOP Dmitry Noskov
  27. 27. After finally advice@Aspectpublic class BankAspect { @Pointcut("execution(public * * (..))") public void anyPublicMethod() {} @After(value="anyPublicMethod() && args(from, to)") public void logAfter(JoinPoint jp, String from, String to) { //to do something }} Spring Framework - AOP Dmitry Noskov
  28. 28. Around advice@Aspectpublic class BankCacheAspect { @Around("@annotation(bank.Cached)") public Object aroundCache(ProceedingJoinPoint joinPoint){ //to do something before Object retVal = joinPoint.proceed(); //to do something after }} Spring Framework - AOP Dmitry Noskov
  29. 29. Aspect and advice ordering order of advice in the same aspect  before  around  after finally  after returning or after throwing Spring interface for ordering aspects  org.springframework.core.Ordered Spring annotation  org.springframework.core.annotation.Order Spring Framework - AOP Dmitry Noskov
  30. 30. XML based AOP Spring Framework - AOP Dmitry Noskov
  31. 31. Declaring an aspect<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="…"> <aop:config> <aop:aspect id="bankAspectId" ref="bankAspect"> <aop:pointcut id="anyPublicMethod" expression="execution(public * * (..))"/> <aop:before pointcut-ref="anyPublicMethod" method="logBefore"/> </aop:aspect> </aop:config> <bean id="bankAspect" class="bank.BankAspect"/></beans> Spring Framework - AOP Dmitry Noskov
  32. 32. How it all works Spring Framework - AOP Dmitry Noskov
  33. 33. Bean in Spring containerStandard OOP implementation Implementation with AOP Spring Framework - AOP Dmitry Noskov
  34. 34. AOP proxiesInvoke directly Invoke via proxy Spring Framework - AOP Dmitry Noskov
  35. 35. How it really works Spring Framework - AOP Dmitry Noskov
  36. 36. Introductions Spring Framework - AOP Dmitry Noskov
  37. 37. Introduction behaviors to bean@Aspectpublic class CalculatorIntroduction { @DeclareParents( value = "calculator.ArithmeticCalculatorImpl", defaultImpl = MaxCalculatorImpl.class) public MaxCalculator maxCalculator; @DeclareParents( value = "calculator.ArithmeticCalculatorImpl", defaultImpl = MinCalculatorImpl.class) public MinCalculator minCalculator;} Spring Framework - AOP Dmitry Noskov
  38. 38. Introduction states to bean@Aspectpublic class BankServiceIntroductionAspect { @DeclareParents( value="bank.BankServiceImpl", defaultImpl=DefaultCounterImpl.class) public Counter mix; @Before("execution(* get*(..)) && this(auditable)") public void useBusinessService(Counter auditable) { auditable.increment(); }} Spring Framework - AOP Dmitry Noskov
  39. 39. Spring AOP vs AspectJSpring AOP AspectJ no need for a special  need AspectJ compiler compilation process or setup LTW support only method  support all pointcuts execution pointcuts advise the execution  advice all domain of operations on objects Spring beans Spring Framework - AOP Dmitry Noskov
  40. 40. @AspectJ vs XML@AspectJ XML has more opportunities,  can be used with any such as combine named JDK level pointcuts encapsulate the  good choice to implementation of the configure enterprise requirement it addresses services in a single place Spring Framework - AOP Dmitry Noskov
  41. 41. Links Useful links  Wiki: Aspect-oriented programming http://en.wikipedia.org/wiki/Aspect-oriented_programming  Spring Reference http://static.springsource.org/spring/docs/3.0.x/spring- framework-reference/html/aop.html  AspectJ home site http://www.eclipse.org/aspectj/ Spring Framework - AOP Dmitry Noskov
  42. 42. Books Spring Framework - AOP Dmitry Noskov
  43. 43. Questions Spring Framework - AOP Dmitry Noskov
  44. 44. The end http://www.linkedin.com/in/noskovd http://www.slideshare.net/analizator/presentations
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×