SlideShare ist ein Scribd-Unternehmen logo
1 von 44
Downloaden Sie, um offline zu lesen
Spring Framework - AOP




                SPRING FRAMEWORK 3.0
Dmitry 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 heart of Spring Framework




                        Spring Framework - AOP   Dmitry Noskov
A simple service method



public Order getOrder(BigDecimal orderId) {
    return (Order) factory.openSession()
                         .get(Order.class, orderId);
}




                            Spring Framework - AOP   Dmitry Noskov
Add permissions check


public 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
Add transaction management
public 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
Add cache
public 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
A similar problem at enterprise level




                 Spring Framework - AOP   Dmitry Noskov
What does AOP solve?

Logging

Validation

Caching

Security

Transactions

Monitoring

Error Handling

Etc…


                 Spring Framework - AOP   Dmitry Noskov
AOP concepts
   aspect
   advice
   pointcut
   join point




                 Spring Framework - AOP   Dmitry Noskov
AOP and OOP

AOP                                            OOP

1.   Aspect – code unit that                   1.   Class – code unit that
     encapsulates pointcuts, advice,                encapsulates methods and
     and attributes                                 attributes
2.   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 bodies
3.   Advice – implementation of                3.   Method bodies –implementation
     cross cutting concern                          of the business logic concerns
4.   Weaver – construct code                   4.   Compiler – convert source code
     (source or object) with advice                 to object code

                                      Spring Framework - AOP   Dmitry Noskov
AOP concepts(2)
   introduction
   target object
   AOP proxy
   weaving
     compile time
     load time

     runtime




                     Spring Framework - AOP   Dmitry Noskov
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
@AspectJ




           Spring Framework - AOP   Dmitry Noskov
Declaring aspect

@Aspect
public class EmptyAspect {
}


<!--<context:annotation-config />-->
<aop:aspectj-autoproxy proxy-target-class="false | true"/>


<bean
class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator">
</bean>


<bean class="example.EmptyAspect"/>


                                        Spring Framework - AOP   Dmitry Noskov
Declaring pointcut




            Spring Framework - AOP   Dmitry Noskov
Pointcut designators
   code based
     execution
     within

     target

     this

     args

     bean




                  Spring Framework - AOP   Dmitry Noskov
Pointcut designators(2)
   annotation based
     @annotation
     @within

     @target

     @args




                       Spring Framework - AOP   Dmitry Noskov
Format of an execution expression
execution(
  modifiers-pattern
  returning-type-pattern
  declaring-type-pattern
  name-pattern(param-pattern)
  throws-pattern
)


                    Spring Framework - AOP   Dmitry Noskov
Simple pointcut expressions
@Aspect
public 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
Execution examples
any public method
execution(public * * (..))"

any method with a name beginning with "get"
execution(* get*(..))

any method defined by the appropriate interface
execution(* bank.BankService.*(..))

any method defined in the appropriate package
execution(* com.epam.pmc.service.*.*(..))

other examples
http://static.springsource.org/spring/docs/3.0.x/spring-framework-
reference/html/aop.html#aop-pointcuts-examples


                                         Spring Framework - AOP   Dmitry Noskov
Declaring advice




           Spring Framework - AOP   Dmitry Noskov
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
Before advice

@Aspect
public class BankAspect {


    @Pointcut("execution(public * * (..))")
    public void anyPublicMethod() {}


    @Before("anyPublicMethod()")
    public void logBefore(JoinPoint joinPoint) {
          //to do something
    }
}



                              Spring Framework - AOP   Dmitry Noskov
After returning advice

@Aspect
public class BankAspect {


    @AfterReturning(
          pointcut="execution(* get*(..))",
          returning="retVal")
    public void logAfter(JoinPoint joinPoint, Object retVal) {
          //to do something
    }
}




                                Spring Framework - AOP   Dmitry Noskov
After throwing advice

@Aspect
public class BankAspect {


    @AfterThrowing(
          pointcut = "execution(* bank..*ServiceImpl.add*(..))",
          throwing = "exception")
    public void afterThrowing(Exception exception) {
          //to do something
    }
}




                              Spring Framework - AOP   Dmitry Noskov
After finally advice

@Aspect
public 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
Around advice

@Aspect
public 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
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
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"
       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
How it all works




            Spring Framework - AOP   Dmitry Noskov
Bean in Spring container

Standard OOP implementation            Implementation with AOP




                              Spring Framework - AOP   Dmitry Noskov
AOP proxies

Invoke 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

@Aspect
public 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
Introduction states to bean

@Aspect
public 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
Spring AOP vs AspectJ

Spring 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
@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
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
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Spring boot
Spring bootSpring boot
Spring boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring AOP in Nutshell
Spring AOP in Nutshell Spring AOP in Nutshell
Spring AOP in Nutshell
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 

Andere mochten auch

Banco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase LiteBanco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase Lite
Fernando Camargo
 
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf Conference
 

Andere mochten auch (20)

Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression Language
 
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
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
 
AOP
AOPAOP
AOP
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - Validation
 
Spring Framework - Web Flow
Spring Framework - Web FlowSpring Framework - Web Flow
Spring Framework - Web Flow
 
Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented Programming
 
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...
 
Boas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful APIBoas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful API
 
Construção de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em JavaConstrução de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em Java
 
Banco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase LiteBanco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase Lite
 
Design de RESTful APIs
Design de RESTful APIsDesign de RESTful APIs
Design de RESTful APIs
 
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
 
Профессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseПрофессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом Enterprise
 
Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникOrm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел Вейник
 
Spring aop concepts
Spring aop conceptsSpring aop concepts
Spring aop concepts
 
JoinCommunity 2 - Projetando um novo app usando user centered design
JoinCommunity 2 - Projetando um novo app usando user centered designJoinCommunity 2 - Projetando um novo app usando user centered design
JoinCommunity 2 - Projetando um novo app usando user centered design
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic Introduction
 

Ähnlich wie Spring Framework - AOP

Aspect-Oriented Programming
Aspect-Oriented ProgrammingAspect-Oriented Programming
Aspect-Oriented Programming
Andrey Bratukhin
 
Spring AOP Introduction
Spring AOP IntroductionSpring AOP Introduction
Spring AOP Introduction
b0ris_1
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
patter
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
Raimonds Simanovskis
 
Dev Day 2019: Mike Sperber – Software Design für die Seele
Dev Day 2019: Mike Sperber – Software Design für die SeeleDev Day 2019: Mike Sperber – Software Design für die Seele
Dev Day 2019: Mike Sperber – Software Design für die Seele
DevDay Dresden
 

Ähnlich wie Spring Framework - AOP (20)

Spring framework part 2
Spring framework  part 2Spring framework  part 2
Spring framework part 2
 
Debugging & profiling node.js
Debugging & profiling node.jsDebugging & profiling node.js
Debugging & profiling node.js
 
Aspect-Oriented Programming
Aspect-Oriented ProgrammingAspect-Oriented Programming
Aspect-Oriented Programming
 
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
 
Serverless Java on Kubernetes
Serverless Java on KubernetesServerless Java on Kubernetes
Serverless Java on Kubernetes
 
Spring AOP Introduction
Spring AOP IntroductionSpring AOP Introduction
Spring AOP Introduction
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Annotation processing tool
Annotation processing toolAnnotation processing tool
Annotation processing tool
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
 
Bulding a reactive game engine with Spring 5 & Couchbase
Bulding a reactive game engine with Spring 5 & CouchbaseBulding a reactive game engine with Spring 5 & Couchbase
Bulding a reactive game engine with Spring 5 & Couchbase
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
 
Introducing spring
Introducing springIntroducing spring
Introducing spring
 
Aspect oriented programming with spring
Aspect oriented programming with springAspect oriented programming with spring
Aspect oriented programming with spring
 
Full Stack Scala
Full Stack ScalaFull Stack Scala
Full Stack Scala
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
Dev Day 2019: Mike Sperber – Software Design für die Seele
Dev Day 2019: Mike Sperber – Software Design für die SeeleDev Day 2019: Mike Sperber – Software Design für die Seele
Dev Day 2019: Mike Sperber – Software Design für die Seele
 
Rapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and PythonRapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and Python
 

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
 

Kürzlich hochgeladen (20)

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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

Spring Framework - AOP

  • 1. Spring Framework - AOP SPRING FRAMEWORK 3.0 Dmitry Noskov Aspect Oriented Programming with Spring
  • 2. Aspect Oriented Programming Spring Framework - AOP Dmitry Noskov
  • 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. A simple service method public Order getOrder(BigDecimal orderId) { return (Order) factory.openSession() .get(Order.class, orderId); } Spring Framework - AOP Dmitry Noskov
  • 5. Add permissions check public 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. Add transaction management public 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. Add cache public 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. A similar problem at enterprise level Spring Framework - AOP Dmitry Noskov
  • 9. What does AOP solve? Logging Validation Caching Security Transactions Monitoring Error Handling Etc… Spring Framework - AOP Dmitry Noskov
  • 10. AOP concepts  aspect  advice  pointcut  join point Spring Framework - AOP Dmitry Noskov
  • 11. AOP and OOP AOP OOP 1. Aspect – code unit that 1. Class – code unit that encapsulates pointcuts, advice, encapsulates methods and and attributes attributes 2. 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 bodies 3. Advice – implementation of 3. Method bodies –implementation cross cutting concern of the business logic concerns 4. Weaver – construct code 4. Compiler – convert source code (source or object) with advice to object code Spring Framework - AOP Dmitry Noskov
  • 12. AOP concepts(2)  introduction  target object  AOP proxy  weaving  compile time  load time  runtime Spring Framework - AOP Dmitry Noskov
  • 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. @AspectJ Spring Framework - AOP Dmitry Noskov
  • 15. Declaring aspect @Aspect public class EmptyAspect { } <!--<context:annotation-config />--> <aop:aspectj-autoproxy proxy-target-class="false | true"/> <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"> </bean> <bean class="example.EmptyAspect"/> Spring Framework - AOP Dmitry Noskov
  • 16. Declaring pointcut Spring Framework - AOP Dmitry Noskov
  • 17. Pointcut designators  code based  execution  within  target  this  args  bean Spring Framework - AOP Dmitry Noskov
  • 18. Pointcut designators(2)  annotation based  @annotation  @within  @target  @args Spring Framework - AOP Dmitry Noskov
  • 19. Format of an execution expression execution( modifiers-pattern returning-type-pattern declaring-type-pattern name-pattern(param-pattern) throws-pattern ) Spring Framework - AOP Dmitry Noskov
  • 20. Simple pointcut expressions @Aspect public 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. Execution examples any public method execution(public * * (..))" any method with a name beginning with "get" execution(* get*(..)) any method defined by the appropriate interface execution(* bank.BankService.*(..)) any method defined in the appropriate package execution(* com.epam.pmc.service.*.*(..)) other examples http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/aop.html#aop-pointcuts-examples Spring Framework - AOP Dmitry Noskov
  • 22. Declaring advice Spring Framework - AOP Dmitry Noskov
  • 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. Before advice @Aspect public class BankAspect { @Pointcut("execution(public * * (..))") public void anyPublicMethod() {} @Before("anyPublicMethod()") public void logBefore(JoinPoint joinPoint) { //to do something } } Spring Framework - AOP Dmitry Noskov
  • 25. After returning advice @Aspect public class BankAspect { @AfterReturning( pointcut="execution(* get*(..))", returning="retVal") public void logAfter(JoinPoint joinPoint, Object retVal) { //to do something } } Spring Framework - AOP Dmitry Noskov
  • 26. After throwing advice @Aspect public class BankAspect { @AfterThrowing( pointcut = "execution(* bank..*ServiceImpl.add*(..))", throwing = "exception") public void afterThrowing(Exception exception) { //to do something } } Spring Framework - AOP Dmitry Noskov
  • 27. After finally advice @Aspect public 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. Around advice @Aspect public 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. 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. XML based AOP Spring Framework - AOP Dmitry Noskov
  • 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. How it all works Spring Framework - AOP Dmitry Noskov
  • 33. Bean in Spring container Standard OOP implementation Implementation with AOP Spring Framework - AOP Dmitry Noskov
  • 34. AOP proxies Invoke directly Invoke via proxy Spring Framework - AOP Dmitry Noskov
  • 35. How it really works Spring Framework - AOP Dmitry Noskov
  • 36. Introductions Spring Framework - AOP Dmitry Noskov
  • 37. Introduction behaviors to bean @Aspect public 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. Introduction states to bean @Aspect public 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. Spring AOP vs AspectJ Spring 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. @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. 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. Books Spring Framework - AOP Dmitry Noskov
  • 43. Questions Spring Framework - AOP Dmitry Noskov
  • 44. The end http://www.linkedin.com/in/noskovd http://www.slideshare.net/analizator/presentations