SlideShare une entreprise Scribd logo
1  sur  44
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCFunnelll
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework tola99
 
Spring boot
Spring bootSpring boot
Spring bootsdeeg
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkHùng Nguyễn Huy
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data AccessDzmitry Naskou
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring SecurityDzmitry Naskou
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué Neis
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introductionJonathan Holloway
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVCIndicThreads
 

Tendances (20)

Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 

En vedette

Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression LanguageDzmitry Naskou
 
Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingYan Cui
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - ValidationDzmitry Naskou
 
Spring Framework - Web Flow
Spring Framework - Web FlowSpring Framework - Web Flow
Spring Framework - Web FlowDzmitry Naskou
 
Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingAmir Kost
 
[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...Dmytro Sokolov
 
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 APIFernando Camargo
 
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 JavaFernando Camargo
 
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 LiteFernando Camargo
 
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf Conference
 
Профессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseПрофессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseAlexander Granin
 
Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникOrm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникAlina Dolgikh
 
Spring aop concepts
Spring aop conceptsSpring aop concepts
Spring aop conceptsRushiBShah
 
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 designFernando Camargo
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionEr. Gaurav Kumar
 

En vedette (20)

Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
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
 
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 (Михаил Шамин)
 
Spring AOP in Nutshell
Spring AOP in Nutshell Spring AOP in Nutshell
Spring AOP in Nutshell
 
Профессиональная разработка в суровом 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
 

Similaire à Spring Framework - AOP

Debugging & profiling node.js
Debugging & profiling node.jsDebugging & profiling node.js
Debugging & profiling node.jstomasperezv
 
Aspect-Oriented Programming
Aspect-Oriented ProgrammingAspect-Oriented Programming
Aspect-Oriented ProgrammingAndrey Bratukhin
 
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 SQLDatabricks
 
Spring AOP Introduction
Spring AOP IntroductionSpring AOP Introduction
Spring AOP Introductionb0ris_1
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworksMD Sayem Ahmed
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207patter
 
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 & CouchbaseAlex Derkach
 
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 OracleRaimonds Simanovskis
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidEmanuele Di Saverio
 
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)JiandSon
 
Aspect oriented programming with spring
Aspect oriented programming with springAspect oriented programming with spring
Aspect oriented programming with springSreenivas Kappala
 
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 SeeleDevDay Dresden
 
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 PythonRick Copeland
 

Similaire à 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
 

Dernier

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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 RobisonAnna Loughnan Colquhoun
 
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 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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 2024Rafal Los
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
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.pptxHampshireHUG
 
[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.pdfhans926745
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
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...Igalia
 
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?Antenna Manufacturer Coco
 
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 Nanonetsnaman860154
 
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.pdfhans926745
 
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...Drew Madelung
 
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.pdfUK Journal
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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 textsMaria Levchenko
 

Dernier (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
[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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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...
 
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?
 
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
 
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
 
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...
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 

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