SlideShare a Scribd company logo
Aspect Oriented Programming
            with

          Spring
Problem area
• How to modularize concerns that span multiple classes
  and layers?

• Examples of cross-cutting concerns:
   –   Transaction management
   –   Logging
   –   Profiling
   –   Security
   –   Internationalisation
Logging: A naive approach

                 public class HibernateEventDAO
                 {
Retrieving log     p
                   private static Log log = LogFactory.getLog( HibernateEventDAO.class );
                                    g g       g      yg     g(
  instance
                   public Integer saveEvent( Event event )
                   {
                     log.info( ”Executing saveEvent( Event ) with argument + ” event.toString() );
Logging method
  executions           Session session = sessionManager.getCurrentSession();

                       return (Integer) session.save( event );
                   }

                   public Event getEvent( Integer id )
                   {
                     log.info( ”Executing getEvent( int )” );

                       Session session = sessionManager.getCurrentSession();

                       return (Event) session.get( Event.class, id );
                   }
Logging: A naive approach

Invokes methods on
     the DAOs
                            EventManager                         Service layer




                                           (method invocation)


 DAOs perform
both logging and
  persistence
   operations
                     PersonDAO        EventDAO               Persistence layer
Shortcomings of naive approach
• Mixes persistence and logging functionality
   – Violates the principle of separation of concerns
   – Increases complexity


• Involves repetition of code
   – Violates the DRY principle
   – Makes it difficult to change


• Couples the LogFactory to the HibernateEventDAO
   – Prevents loosely coupled design
   – Makes re-use and testing problematic
Logging: The AOP approach

                            EventManager                            Service layer



                                              (method invocation)
 Intercepts method
  invocations and
  performs logging
                            AOP interceptor




 DAOs perform
persistence only
                     PersonDAO          EventDAO                Persistence layer
Advantages of AOP approach
• Separates persistence and logging functionality
   – The logging concern taken care of by the interceptor
   – Decreases complexity


• Promotes code reuse and modularization
   – The AOP interceptor is used by all methods in the DAOs
   – Makes it easier to change


• Decouples the LogFactory from the DAO impl’s
   – The HibernateEventDAO is unaware of being logged
   – Makes re-use and testing simple
Aspect Oriented Programming
• Definition: Enables encapsulation of functionality that
  affects multiple classes in separate units

• Complements object oriented programming

• Most popular implementation for Java is AspectJ
   – Aspect oriented extension for Java
   – Available as Eclipse plugin and standalone IDE
Spring overview
AOP with Spring
• The AOP framework is a key component of Spring

• Ai
  Aims at providing i t
        t     idi integration b t
                         ti between AOP and I C
                                          d IoC

• Integrates – but doesn’t compete – with AspectJ
                   doesn t

• Provides two techniques for defining aspects:
   – @AspectJ annotation
   – XML schema-based
AOP concepts
• Aspect
   – A concern that cuts across multiple classes and layers

• Join point
   – A method invocation during t e e ecut o o a p og a
        et od    ocat o du g the execution of program

• Advice
   – An implementation of a concern represented as an interceptor

• Pointcut
   – An expression mapped to a join point
@AspectJ support
 • Style of declaring aspects as regular Java classes with
   Java 5 annotations
 • R
   Requires aspectjweaver and aspectjrt on th classpath
         i          tj         d       tj t  the l       th
 • Enabled by including the following information in the
   Spring configuration file:


<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="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

 <aop:aspectj-autoproxy/>
Declaring an aspect
• A concern that cuts across multiple classses and layers


  @Aspect annotation         import org.aspectj.lang.annotation.Aspect;

                             @Aspect
  Any bean with a class
                             p
                             public class LoggingInterceptor
                                            gg g        p
 annotated as an aspect
       t t d             t   {
   will be automatically       // ...
   detected by Spring        }




 Regular bean definition
 pointing t a b
   i ti to bean class
                    l        <bean id="loggingInterceptor"
    with the @Aspect           class="no.uio.inf5750.interceptor.LoggingInterceptor"/>
        annotation
Declaring a pointcut
• An expression mapped to a join point (method
  invocation)

                                        AspectJ pointcut expression that determines
                                           which method executions to intercept




     Indicated by the
    @Pointcut
    @P i t t annotation
                   t ti          @Aspect
                                 Public class LoggingInterceptor
                                 {
                                   @Pointcut( "execution( * no.uio.inf5750.dao.*.*(..) )" )
                                   private void daoLayer() {}
Pointcut signature provided by
 a regular method definition
Pointcut expression pattern
• The execution pointcut designator is used most often

                                                            Method name.
  Pointcut                     Can use * to
                                                             Can use * to              Exception type.
 designator.                  match any type.
                                                            match any type.              Optional.
 Mandatory.                    Mandatory.
                                                             Mandatory.




               designator( modifiers return-type declaring-type name(params) throws )
                   g     (                   yp          g yp       (p     )




                                                                              () = no params.
                                            Package and
                                            P k         d
               Public, private,                                          (..) = any nr of params.
                                            class name.
                etc. Optional.                                            (*,String) = one of any
                                              Optional.
                                                                            type, one of String.
Pointcut expression examples

        Any public method           execution( public * *(..) )




    Any public method defined
                                    execution( public * no.uio.inf5750.dao.*.*(..) )
       in the dao package



    Any method with a name
                                    execution( * save*(..) )
      beginning with save



    Any method defined by the
                                    execution( * no.uio.inf5750.dao.EventDAO.*(*) )
                                          i (        i i f5750 d E       DAO *(*)
EventDAO interface with one param
Declaring advice
• Implementation of concern represented as an interceptor
• Types
    – Before advice
    – After advice                                                  Provides access to the
                                                                current join point (target object,
    – Around advice                                           description of advised method, ect. )
                                                              d    i ti    f d i d       th d     t




                       @Aspect
  Before advice.       public class LoggingInterceptor
Executes before the    {
                         @Before( ”no.uio.inf5750.interceptor.LoggingInterceptor.daoLayer()” )
 matched method
          method.        public void intercept( JoinPoint joinPoint )
Declared using the       {
@Before annotation.         log.info( ”Executing ” + joinPoint.getSignature().toShortString() );
                         }
After returning & throwing advice
After returning advice.   @Aspect
  Executes after the      public class LoggingInterceptor
matched method has        {
                            @AfterReturning( ”no.uio.inf5750.interceptor.LoggingInterceptor.daoLayer()” )
  returned normally.
            normally        public void i t
                               bli    id intercept( J i P i t j i P i t )
                                                 t( JoinPoint joinPoint
 Declared using the         {
  @AfterReturning              log.info( ”Executed successfully ” + joinPoint.getSignature().toShortString() );
      annotation.           }




                          @Aspect
After throwing advice.    public class LoggingInterceptor
  Executes after the      {
matched method has          @AfterThrowing( ”no.uio.inf5750.interceptor.LoggingInterceptor.daoLayer()” )
thrown an exception.        public void intercept( JoinPoint joinPoint )
   Declared using           {
                               log.info( ”Execution failed ” + joinPoint.getSignature().toShortString() );
  @AfterThrowing.
                            }
Around advice
• Can do work both before and after the method executes
• Determines when, how and if the method is executed
                           @Aspect
                           public class LoggingInterceptor
                           {
                             @Around( ”
                             @A        d( ”no.uio.inf5750.interceptor.LoggingInterceptor.daoLayer()” )
                                               i i f5750 i t       t L    i I t       t d L          ()”
    Around advice.           public void intercept( ProceedingJoinPoint joinPoint )
                             {
   The first parameter          log.info( ”Executing ” + joinPoint.getSignature().toShortString() );
     must be of type
 ProceedingJoinPoint –          try
                                {
calling proceed() causes          joinPoint.proceed();
  the target method to          }
         execute.               catch ( Throwable t )
                                {
  Declared using the              log.error( t.getMessage() + ”: ” + joinPoint.getSignature().toShortString() );
 @Around annotation.              throw t;
                                }

                                log.info( ”Successfully executed ” + joinPoint.getSignature().toShortString() );
                           }
Accessing arguments
• The args binding form makes argument values available
  to the advice body
• A
  Argument name must correspond with advice method
           t          t         d ith d i       th d
  signature


   Makes the object       @Aspect
 argument available
    g                     public class LoggingInterceptor
  to the advice body      {
                            @Before( ”no.uio.inf5750.interceptor.LoggingInterceptor.daoLayer() and ” +
                               ”args( object, .. )” )
                            public void intercept( JoinPoint joinPoint, Object object )
                            {
                               log.info( ”Executing ” + joinPoint.getSignature().toShortString() +
 Will restrict matching           ” with argument ” + object.toString() );
 to methods declaring       }
at least one parameter
Accessing return values
• The returning binding form makes the return value
  available to the advice body
• R t
  Return value name must correspond with advice method
            l              t        d ith d i       th d
  signature

  Makes the object        @Aspect
    return value          public class LoggingInterceptor
  available to the        {
    advice body             @AfterReturning(
                               pointcut=”no.uio.inf5750.interceptor.LoggingInterceptor.daoLayer() ”,
                               returning=”object” )
                            public void intercept( JoinPoint joinPoint, Object object )
                            {
 Will restrict matching        log.info( ”Executed ” + joinPoint.getSignature().toShortString() +
to methods returning a            ” with return value ” + object.toString() );
                            }
value of specified type
Schema-based
          Schema based support
• L t you d fi aspects using th aop namespace t
  Lets     define       t     i the           tags
  in the Spring configuration file

• Enabled by importing the Spring aop schema

• Pointcut expressions and advice types similar to
  @AspectJ

• Suitable when:
   – Y are unable to use J
     You        bl        Java 5
   – Prefer an XML based format
Declaring an aspect
• An aspect is a regular Java object defined as a bean in
  the Spring context

 All configuration inside
an <aop:config> element
                            <aop:config>

                              <aop:aspect id=”logging” ref=”loggingInterceptor”>
 Aspect declared using
   p                    g
   the <aop:aspect>           </aop:aspect>
element. Backing bean       </aop:config>
      is referenced
  with the ref attribute.

                            <bean id="loggingInterceptor"
                              class="no.uio.inf5750.interceptor.LoggingInterceptor"/>

Regular bean definition
Declaring a pointcut
• Pointcut expressions are similar to @AspectJ
• A pointcut can be shared across advice



Pointcut declared inside
 <aop:config> element
       using the           <aop:config>
<aop:pointcut> element
                             <aop:pointcut id=”daoLayer”
                             <aop pointc t id ”daoLa er”
                               expression="execution( * no.uio.inf5750.dao.*.*(..) )”/>

                           </aop:config>
 Can also be defined
   inside aspects
Declaring advice
  Before advice.       <aop:aspect id=”logging” ref=”loggingInterceptor”>

                         <aop:before pointcut-ref=”daoLayer” method=”intercept”/>
Declared inside an
     aspect.
     aspect            </aop:aspect>




                               Refers to pointcut                       Refers to advising method




                       public class LoggingInterceptor
Advice is a regular    {
    Java class           public void intercept( JoinPoint joinPoint )
                         {
                            // Do some useful intercepting work
                         }
                       }
Declaring advice
                          <aop:aspect id=”logging” ref=”loggingInterceptor”>

After returning advice      <aop:after-returning pointcut-ref=”daoLayer” method=”intercept”/>

                          </aop:aspect>




                          <aop:aspect id=”logging” ref=”loggingInterceptor”>

After throwing advice       <aop:after-throwing pointcut-ref=”daoLayer” method=”intercept”/>

                          </aop:aspect>




                          <aop:aspect id=”logging” ref=”loggingInterceptor”>

   Around advice            <aop:around pointcut-ref=”daoLayer” method=”intercept”/>

                          </aop:aspect>
AOP - Transaction Management
                              public i
                                bli interface T
                                         f    TransactionManager
                                                      i M
  TransactionManager          {
       interface                public void enter();
                                public void abort();
                                p
                                public void leave();
                                                 ();



                              @Aspect
Transaction management        public interface TransactionInterceptor
    implemented with          {
      around advice             @Around( ”execution( public no.uio.inf5750.dao.*.*(..) )” ) // In-line pointcut
                                public void intercept( ProceedingJoinPoint joinPoint )
                                {
                                   transactionManager.enter();
                                                    g         ();
   Enters transaction
before method invocation           try
                                   {
                                     joinPoint.proceed();
                                   }
  Aborts and rolls back            catch ( Throwable t )
transaction if method fails        {
                                     transactionManager.abort();
                                     throw t;
                                   }
 Leaves transaction if
method completes norm.             transactionManager.leave();
@AspectJ or Schema based?
                Schema-based?
• Advantages of schema style
   – Can be used with any JDK level
   – Clearer which aspects are present in the system


• Advantages of @AspectJ style
   – One single unit where information is encapsulated for an aspect
   – Possible to combine named pointcuts
   – Can be understood by AspectJ – easy to migrate later
Summary
• Key components in AOP are aspect, pointcut, join point,
  and advice

• AOP lets you encapsulate functionality that affects
  multiple classes in an interceptor

• Advantages of AOP:
   – Promotes separation of concern
   – Promotes code reuse and modularization
   – Promotes loosely coupled design
References
• The Spring reference documentation - Chapter 6
   – www.springframework.org


• AOP example code
   – www ifi uio no/INF5750/h07/undervisningsplan xml
     www.ifi.uio.no/INF5750/h07/undervisningsplan.xml

More Related Content

What's hot

Method Shelters : Another Way to Resolve Class Extension Conflicts
Method Shelters : Another Way to Resolve Class Extension Conflicts Method Shelters : Another Way to Resolve Class Extension Conflicts
Method Shelters : Another Way to Resolve Class Extension Conflicts
S Akai
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
manish kumar
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
guest5c8bd1
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
manish kumar
 
Effective Java - Enum and Annotations
Effective Java - Enum and AnnotationsEffective Java - Enum and Annotations
Effective Java - Enum and Annotations
Roshan Deniyage
 
Java cheat sheet
Java cheat sheet Java cheat sheet
Java cheat sheet
Saifur Rahman
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
javeed_mhd
 
Parte II Objective C
Parte II   Objective CParte II   Objective C
Parte II Objective C
Paolo Quadrani
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Ranel Padon
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statement
manish kumar
 
Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
Diksha Bhargava
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
Arslan Arshad
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Java
hendersk
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2Vince Vo
 

What's hot (20)

Gdb cheat sheet
Gdb cheat sheetGdb cheat sheet
Gdb cheat sheet
 
Method Shelters : Another Way to Resolve Class Extension Conflicts
Method Shelters : Another Way to Resolve Class Extension Conflicts Method Shelters : Another Way to Resolve Class Extension Conflicts
Method Shelters : Another Way to Resolve Class Extension Conflicts
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
Effective Java - Enum and Annotations
Effective Java - Enum and AnnotationsEffective Java - Enum and Annotations
Effective Java - Enum and Annotations
 
Java cheat sheet
Java cheat sheet Java cheat sheet
Java cheat sheet
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Parte II Objective C
Parte II   Objective CParte II   Objective C
Parte II Objective C
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statement
 
Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Java
 
Unit 8
Unit 8Unit 8
Unit 8
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2
 

Viewers also liked

Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented Programming
Yan Cui
 
Spring AOP Introduction
Spring AOP IntroductionSpring AOP Introduction
Spring AOP Introductionb0ris_1
 
AOP
AOPAOP
Spring AOP
Spring AOPSpring AOP
Spring AOP
Jeroen Rosenberg
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
Anumod Kumar
 
Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented Programming
Amir Kost
 
Spring AOP in Nutshell
Spring AOP in Nutshell Spring AOP in Nutshell
Spring AOP in Nutshell
Onkar Deshpande
 
Introduction to AOP, AspectJ, and Explicit Join Points
Introduction to AOP, AspectJ, and Explicit Join PointsIntroduction to AOP, AspectJ, and Explicit Join Points
Introduction to AOP, AspectJ, and Explicit Join Points
Kevin Hoffman
 
Advanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, IdiomsAdvanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, Idioms
Clint Edmonson
 
Introduction to Object-Oriented Programming & Design Principles (TCF 2014)
Introduction to Object-Oriented Programming & Design Principles (TCF 2014)Introduction to Object-Oriented Programming & Design Principles (TCF 2014)
Introduction to Object-Oriented Programming & Design Principles (TCF 2014)
Michael Redlich
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
Sangharsh agarwal
 
C# OOP Advanced Concepts
C# OOP Advanced ConceptsC# OOP Advanced Concepts
C# OOP Advanced Concepts
agni_agbc
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
BG Java EE Course
 
Object Oriented Analysis and Design with UML2 part1
Object Oriented Analysis and Design with UML2 part1Object Oriented Analysis and Design with UML2 part1
Object Oriented Analysis and Design with UML2 part1
Haitham Raik
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
Dzmitry Naskou
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Veerabadra Badra
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and DesignHaitham El-Ghareeb
 

Viewers also liked (18)

Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented Programming
 
Spring AOP Introduction
Spring AOP IntroductionSpring AOP Introduction
Spring AOP Introduction
 
AOP
AOPAOP
AOP
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
 
Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented Programming
 
Aop spring
Aop springAop spring
Aop spring
 
Spring AOP in Nutshell
Spring AOP in Nutshell Spring AOP in Nutshell
Spring AOP in Nutshell
 
Introduction to AOP, AspectJ, and Explicit Join Points
Introduction to AOP, AspectJ, and Explicit Join PointsIntroduction to AOP, AspectJ, and Explicit Join Points
Introduction to AOP, AspectJ, and Explicit Join Points
 
Advanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, IdiomsAdvanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, Idioms
 
Introduction to Object-Oriented Programming & Design Principles (TCF 2014)
Introduction to Object-Oriented Programming & Design Principles (TCF 2014)Introduction to Object-Oriented Programming & Design Principles (TCF 2014)
Introduction to Object-Oriented Programming & Design Principles (TCF 2014)
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
C# OOP Advanced Concepts
C# OOP Advanced ConceptsC# OOP Advanced Concepts
C# OOP Advanced Concepts
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
Object Oriented Analysis and Design with UML2 part1
Object Oriented Analysis and Design with UML2 part1Object Oriented Analysis and Design with UML2 part1
Object Oriented Analysis and Design with UML2 part1
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and Design
 

Similar to Aspect oriented programming_with_spring

Aspect oriented programming with spring
Aspect oriented programming with springAspect oriented programming with spring
Aspect oriented programming with spring
Sreenivas Kappala
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
Serhii Kartashov
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
David McCarter
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processor
Bartosz Kosarzycki
 
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHave Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHoward Lewis Ship
 
Annotations Processor Tools (APT)
Annotations Processor Tools (APT)Annotations Processor Tools (APT)
Annotations Processor Tools (APT)
Txus Ballesteros Martín
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
Yakov Fain
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
Rahman USTA
 
Java 8 and beyond, a scala story
Java 8 and beyond, a scala storyJava 8 and beyond, a scala story
Java 8 and beyond, a scala story
ittaiz
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
Oliver Gierke
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
Codemotion
 
L04 base patterns
L04 base patternsL04 base patterns
L04 base patterns
Ólafur Andri Ragnarsson
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
VijalJain3
 
Advance python
Advance pythonAdvance python
Advance python
pulkit agrawal
 
45 aop-programming
45 aop-programming45 aop-programming
45 aop-programmingdaotuan85
 
Annotation processing
Annotation processingAnnotation processing
Annotation processing
Florent Champigny
 
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJSeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJTed Leung
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
Ajit Mali
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
VGaneshKarthikeyan
 

Similar to Aspect oriented programming_with_spring (20)

Aspect oriented programming with spring
Aspect oriented programming with springAspect oriented programming with spring
Aspect oriented programming with spring
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processor
 
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHave Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
 
Annotations Processor Tools (APT)
Annotations Processor Tools (APT)Annotations Processor Tools (APT)
Annotations Processor Tools (APT)
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Java 8 and beyond, a scala story
Java 8 and beyond, a scala storyJava 8 and beyond, a scala story
Java 8 and beyond, a scala story
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
L04 base patterns
L04 base patternsL04 base patterns
L04 base patterns
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochez
 
Advance python
Advance pythonAdvance python
Advance python
 
45 aop-programming
45 aop-programming45 aop-programming
45 aop-programming
 
Annotation processing
Annotation processingAnnotation processing
Annotation processing
 
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJSeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
 

More from Guo Albert

AWS IAM (Identity and Access Management) Policy Simulator
AWS IAM (Identity and Access Management) Policy SimulatorAWS IAM (Identity and Access Management) Policy Simulator
AWS IAM (Identity and Access Management) Policy Simulator
Guo Albert
 
TOEIC 準備心得
TOEIC 準備心得TOEIC 準備心得
TOEIC 準備心得
Guo Albert
 
DBM專案環境建置
DBM專案環境建置DBM專案環境建置
DBM專案環境建置
Guo Albert
 
JPA Optimistic Locking With @Version
JPA Optimistic Locking With @VersionJPA Optimistic Locking With @Version
JPA Optimistic Locking With @VersionGuo Albert
 
OCEJPA Study Notes
OCEJPA Study NotesOCEJPA Study Notes
OCEJPA Study NotesGuo Albert
 
OCEJPA(1Z0-898) Preparation Tips
OCEJPA(1Z0-898) Preparation TipsOCEJPA(1Z0-898) Preparation Tips
OCEJPA(1Z0-898) Preparation TipsGuo Albert
 
JPA lifecycle events practice
JPA lifecycle events practiceJPA lifecycle events practice
JPA lifecycle events practiceGuo Albert
 
XDate - a modern java-script date library
XDate -  a modern java-script date libraryXDate -  a modern java-script date library
XDate - a modern java-script date library
Guo Albert
 
How to avoid check style errors
How to avoid check style errorsHow to avoid check style errors
How to avoid check style errorsGuo Albert
 
NIG系統報表開發指南
NIG系統報表開發指南NIG系統報表開發指南
NIG系統報表開發指南Guo Albert
 
Ease Your Effort of Putting Data into History Table
Ease Your Effort of Putting Data into History TableEase Your Effort of Putting Data into History Table
Ease Your Effort of Putting Data into History TableGuo Albert
 
NIG 系統開發指引
NIG 系統開發指引NIG 系統開發指引
NIG 系統開發指引Guo Albert
 
NIG系統開發文件閱讀步驟
NIG系統開發文件閱讀步驟NIG系統開發文件閱讀步驟
NIG系統開發文件閱讀步驟Guo Albert
 
Form Bean Creation Process for NIG System
Form Bean Creation Process for NIG SystemForm Bean Creation Process for NIG System
Form Bean Creation Process for NIG SystemGuo Albert
 
A Short Intorduction to JasperReports
A Short Intorduction to JasperReportsA Short Intorduction to JasperReports
A Short Intorduction to JasperReportsGuo Albert
 
Apply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report ImplementationApply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report ImplementationGuo Albert
 
Utilize Commons BeansUtils to do copy object
Utilize Commons BeansUtils to do copy objectUtilize Commons BeansUtils to do copy object
Utilize Commons BeansUtils to do copy objectGuo Albert
 
Apply my eclipse to do entity class generation
Apply my eclipse to do entity class generationApply my eclipse to do entity class generation
Apply my eclipse to do entity class generationGuo Albert
 
Nig project setup quickly tutorial
Nig project setup quickly tutorialNig project setup quickly tutorial
Nig project setup quickly tutorialGuo Albert
 
Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplateGuo Albert
 

More from Guo Albert (20)

AWS IAM (Identity and Access Management) Policy Simulator
AWS IAM (Identity and Access Management) Policy SimulatorAWS IAM (Identity and Access Management) Policy Simulator
AWS IAM (Identity and Access Management) Policy Simulator
 
TOEIC 準備心得
TOEIC 準備心得TOEIC 準備心得
TOEIC 準備心得
 
DBM專案環境建置
DBM專案環境建置DBM專案環境建置
DBM專案環境建置
 
JPA Optimistic Locking With @Version
JPA Optimistic Locking With @VersionJPA Optimistic Locking With @Version
JPA Optimistic Locking With @Version
 
OCEJPA Study Notes
OCEJPA Study NotesOCEJPA Study Notes
OCEJPA Study Notes
 
OCEJPA(1Z0-898) Preparation Tips
OCEJPA(1Z0-898) Preparation TipsOCEJPA(1Z0-898) Preparation Tips
OCEJPA(1Z0-898) Preparation Tips
 
JPA lifecycle events practice
JPA lifecycle events practiceJPA lifecycle events practice
JPA lifecycle events practice
 
XDate - a modern java-script date library
XDate -  a modern java-script date libraryXDate -  a modern java-script date library
XDate - a modern java-script date library
 
How to avoid check style errors
How to avoid check style errorsHow to avoid check style errors
How to avoid check style errors
 
NIG系統報表開發指南
NIG系統報表開發指南NIG系統報表開發指南
NIG系統報表開發指南
 
Ease Your Effort of Putting Data into History Table
Ease Your Effort of Putting Data into History TableEase Your Effort of Putting Data into History Table
Ease Your Effort of Putting Data into History Table
 
NIG 系統開發指引
NIG 系統開發指引NIG 系統開發指引
NIG 系統開發指引
 
NIG系統開發文件閱讀步驟
NIG系統開發文件閱讀步驟NIG系統開發文件閱讀步驟
NIG系統開發文件閱讀步驟
 
Form Bean Creation Process for NIG System
Form Bean Creation Process for NIG SystemForm Bean Creation Process for NIG System
Form Bean Creation Process for NIG System
 
A Short Intorduction to JasperReports
A Short Intorduction to JasperReportsA Short Intorduction to JasperReports
A Short Intorduction to JasperReports
 
Apply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report ImplementationApply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report Implementation
 
Utilize Commons BeansUtils to do copy object
Utilize Commons BeansUtils to do copy objectUtilize Commons BeansUtils to do copy object
Utilize Commons BeansUtils to do copy object
 
Apply my eclipse to do entity class generation
Apply my eclipse to do entity class generationApply my eclipse to do entity class generation
Apply my eclipse to do entity class generation
 
Nig project setup quickly tutorial
Nig project setup quickly tutorialNig project setup quickly tutorial
Nig project setup quickly tutorial
 
Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplate
 

Recently uploaded

Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
kitab khulasah nurul yaqin jilid 1 - 2.pptx
kitab khulasah nurul yaqin jilid 1 - 2.pptxkitab khulasah nurul yaqin jilid 1 - 2.pptx
kitab khulasah nurul yaqin jilid 1 - 2.pptx
datarid22
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
What is the purpose of studying mathematics.pptx
What is the purpose of studying mathematics.pptxWhat is the purpose of studying mathematics.pptx
What is the purpose of studying mathematics.pptx
christianmathematics
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
AG2 Design
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
NelTorrente
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
Fresher’s Quiz 2023 at GMC Nizamabad.pptx
Fresher’s Quiz 2023 at GMC Nizamabad.pptxFresher’s Quiz 2023 at GMC Nizamabad.pptx
Fresher’s Quiz 2023 at GMC Nizamabad.pptx
SriSurya50
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Reflective and Evaluative Practice...pdf
Reflective and Evaluative Practice...pdfReflective and Evaluative Practice...pdf
Reflective and Evaluative Practice...pdf
amberjdewit93
 

Recently uploaded (20)

Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
kitab khulasah nurul yaqin jilid 1 - 2.pptx
kitab khulasah nurul yaqin jilid 1 - 2.pptxkitab khulasah nurul yaqin jilid 1 - 2.pptx
kitab khulasah nurul yaqin jilid 1 - 2.pptx
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
What is the purpose of studying mathematics.pptx
What is the purpose of studying mathematics.pptxWhat is the purpose of studying mathematics.pptx
What is the purpose of studying mathematics.pptx
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
Fresher’s Quiz 2023 at GMC Nizamabad.pptx
Fresher’s Quiz 2023 at GMC Nizamabad.pptxFresher’s Quiz 2023 at GMC Nizamabad.pptx
Fresher’s Quiz 2023 at GMC Nizamabad.pptx
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Reflective and Evaluative Practice...pdf
Reflective and Evaluative Practice...pdfReflective and Evaluative Practice...pdf
Reflective and Evaluative Practice...pdf
 

Aspect oriented programming_with_spring

  • 2. Problem area • How to modularize concerns that span multiple classes and layers? • Examples of cross-cutting concerns: – Transaction management – Logging – Profiling – Security – Internationalisation
  • 3. Logging: A naive approach public class HibernateEventDAO { Retrieving log p private static Log log = LogFactory.getLog( HibernateEventDAO.class ); g g g yg g( instance public Integer saveEvent( Event event ) { log.info( ”Executing saveEvent( Event ) with argument + ” event.toString() ); Logging method executions Session session = sessionManager.getCurrentSession(); return (Integer) session.save( event ); } public Event getEvent( Integer id ) { log.info( ”Executing getEvent( int )” ); Session session = sessionManager.getCurrentSession(); return (Event) session.get( Event.class, id ); }
  • 4. Logging: A naive approach Invokes methods on the DAOs EventManager Service layer (method invocation) DAOs perform both logging and persistence operations PersonDAO EventDAO Persistence layer
  • 5. Shortcomings of naive approach • Mixes persistence and logging functionality – Violates the principle of separation of concerns – Increases complexity • Involves repetition of code – Violates the DRY principle – Makes it difficult to change • Couples the LogFactory to the HibernateEventDAO – Prevents loosely coupled design – Makes re-use and testing problematic
  • 6. Logging: The AOP approach EventManager Service layer (method invocation) Intercepts method invocations and performs logging AOP interceptor DAOs perform persistence only PersonDAO EventDAO Persistence layer
  • 7. Advantages of AOP approach • Separates persistence and logging functionality – The logging concern taken care of by the interceptor – Decreases complexity • Promotes code reuse and modularization – The AOP interceptor is used by all methods in the DAOs – Makes it easier to change • Decouples the LogFactory from the DAO impl’s – The HibernateEventDAO is unaware of being logged – Makes re-use and testing simple
  • 8. Aspect Oriented Programming • Definition: Enables encapsulation of functionality that affects multiple classes in separate units • Complements object oriented programming • Most popular implementation for Java is AspectJ – Aspect oriented extension for Java – Available as Eclipse plugin and standalone IDE
  • 10. AOP with Spring • The AOP framework is a key component of Spring • Ai Aims at providing i t t idi integration b t ti between AOP and I C d IoC • Integrates – but doesn’t compete – with AspectJ doesn t • Provides two techniques for defining aspects: – @AspectJ annotation – XML schema-based
  • 11. AOP concepts • Aspect – A concern that cuts across multiple classes and layers • Join point – A method invocation during t e e ecut o o a p og a et od ocat o du g the execution of program • Advice – An implementation of a concern represented as an interceptor • Pointcut – An expression mapped to a join point
  • 12. @AspectJ support • Style of declaring aspects as regular Java classes with Java 5 annotations • R Requires aspectjweaver and aspectjrt on th classpath i tj d tj t the l th • Enabled by including the following information in the Spring configuration file: <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=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <aop:aspectj-autoproxy/>
  • 13. Declaring an aspect • A concern that cuts across multiple classses and layers @Aspect annotation import org.aspectj.lang.annotation.Aspect; @Aspect Any bean with a class p public class LoggingInterceptor gg g p annotated as an aspect t t d t { will be automatically // ... detected by Spring } Regular bean definition pointing t a b i ti to bean class l <bean id="loggingInterceptor" with the @Aspect class="no.uio.inf5750.interceptor.LoggingInterceptor"/> annotation
  • 14. Declaring a pointcut • An expression mapped to a join point (method invocation) AspectJ pointcut expression that determines which method executions to intercept Indicated by the @Pointcut @P i t t annotation t ti @Aspect Public class LoggingInterceptor { @Pointcut( "execution( * no.uio.inf5750.dao.*.*(..) )" ) private void daoLayer() {} Pointcut signature provided by a regular method definition
  • 15. Pointcut expression pattern • The execution pointcut designator is used most often Method name. Pointcut Can use * to Can use * to Exception type. designator. match any type. match any type. Optional. Mandatory. Mandatory. Mandatory. designator( modifiers return-type declaring-type name(params) throws ) g ( yp g yp (p ) () = no params. Package and P k d Public, private, (..) = any nr of params. class name. etc. Optional. (*,String) = one of any Optional. type, one of String.
  • 16. Pointcut expression examples Any public method execution( public * *(..) ) Any public method defined execution( public * no.uio.inf5750.dao.*.*(..) ) in the dao package Any method with a name execution( * save*(..) ) beginning with save Any method defined by the execution( * no.uio.inf5750.dao.EventDAO.*(*) ) i ( i i f5750 d E DAO *(*) EventDAO interface with one param
  • 17. Declaring advice • Implementation of concern represented as an interceptor • Types – Before advice – After advice Provides access to the current join point (target object, – Around advice description of advised method, ect. ) d i ti f d i d th d t @Aspect Before advice. public class LoggingInterceptor Executes before the { @Before( ”no.uio.inf5750.interceptor.LoggingInterceptor.daoLayer()” ) matched method method. public void intercept( JoinPoint joinPoint ) Declared using the { @Before annotation. log.info( ”Executing ” + joinPoint.getSignature().toShortString() ); }
  • 18. After returning & throwing advice After returning advice. @Aspect Executes after the public class LoggingInterceptor matched method has { @AfterReturning( ”no.uio.inf5750.interceptor.LoggingInterceptor.daoLayer()” ) returned normally. normally public void i t bli id intercept( J i P i t j i P i t ) t( JoinPoint joinPoint Declared using the { @AfterReturning log.info( ”Executed successfully ” + joinPoint.getSignature().toShortString() ); annotation. } @Aspect After throwing advice. public class LoggingInterceptor Executes after the { matched method has @AfterThrowing( ”no.uio.inf5750.interceptor.LoggingInterceptor.daoLayer()” ) thrown an exception. public void intercept( JoinPoint joinPoint ) Declared using { log.info( ”Execution failed ” + joinPoint.getSignature().toShortString() ); @AfterThrowing. }
  • 19. Around advice • Can do work both before and after the method executes • Determines when, how and if the method is executed @Aspect public class LoggingInterceptor { @Around( ” @A d( ”no.uio.inf5750.interceptor.LoggingInterceptor.daoLayer()” ) i i f5750 i t t L i I t t d L ()” Around advice. public void intercept( ProceedingJoinPoint joinPoint ) { The first parameter log.info( ”Executing ” + joinPoint.getSignature().toShortString() ); must be of type ProceedingJoinPoint – try { calling proceed() causes joinPoint.proceed(); the target method to } execute. catch ( Throwable t ) { Declared using the log.error( t.getMessage() + ”: ” + joinPoint.getSignature().toShortString() ); @Around annotation. throw t; } log.info( ”Successfully executed ” + joinPoint.getSignature().toShortString() ); }
  • 20. Accessing arguments • The args binding form makes argument values available to the advice body • A Argument name must correspond with advice method t t d ith d i th d signature Makes the object @Aspect argument available g public class LoggingInterceptor to the advice body { @Before( ”no.uio.inf5750.interceptor.LoggingInterceptor.daoLayer() and ” + ”args( object, .. )” ) public void intercept( JoinPoint joinPoint, Object object ) { log.info( ”Executing ” + joinPoint.getSignature().toShortString() + Will restrict matching ” with argument ” + object.toString() ); to methods declaring } at least one parameter
  • 21. Accessing return values • The returning binding form makes the return value available to the advice body • R t Return value name must correspond with advice method l t d ith d i th d signature Makes the object @Aspect return value public class LoggingInterceptor available to the { advice body @AfterReturning( pointcut=”no.uio.inf5750.interceptor.LoggingInterceptor.daoLayer() ”, returning=”object” ) public void intercept( JoinPoint joinPoint, Object object ) { Will restrict matching log.info( ”Executed ” + joinPoint.getSignature().toShortString() + to methods returning a ” with return value ” + object.toString() ); } value of specified type
  • 22. Schema-based Schema based support • L t you d fi aspects using th aop namespace t Lets define t i the tags in the Spring configuration file • Enabled by importing the Spring aop schema • Pointcut expressions and advice types similar to @AspectJ • Suitable when: – Y are unable to use J You bl Java 5 – Prefer an XML based format
  • 23. Declaring an aspect • An aspect is a regular Java object defined as a bean in the Spring context All configuration inside an <aop:config> element <aop:config> <aop:aspect id=”logging” ref=”loggingInterceptor”> Aspect declared using p g the <aop:aspect> </aop:aspect> element. Backing bean </aop:config> is referenced with the ref attribute. <bean id="loggingInterceptor" class="no.uio.inf5750.interceptor.LoggingInterceptor"/> Regular bean definition
  • 24. Declaring a pointcut • Pointcut expressions are similar to @AspectJ • A pointcut can be shared across advice Pointcut declared inside <aop:config> element using the <aop:config> <aop:pointcut> element <aop:pointcut id=”daoLayer” <aop pointc t id ”daoLa er” expression="execution( * no.uio.inf5750.dao.*.*(..) )”/> </aop:config> Can also be defined inside aspects
  • 25. Declaring advice Before advice. <aop:aspect id=”logging” ref=”loggingInterceptor”> <aop:before pointcut-ref=”daoLayer” method=”intercept”/> Declared inside an aspect. aspect </aop:aspect> Refers to pointcut Refers to advising method public class LoggingInterceptor Advice is a regular { Java class public void intercept( JoinPoint joinPoint ) { // Do some useful intercepting work } }
  • 26. Declaring advice <aop:aspect id=”logging” ref=”loggingInterceptor”> After returning advice <aop:after-returning pointcut-ref=”daoLayer” method=”intercept”/> </aop:aspect> <aop:aspect id=”logging” ref=”loggingInterceptor”> After throwing advice <aop:after-throwing pointcut-ref=”daoLayer” method=”intercept”/> </aop:aspect> <aop:aspect id=”logging” ref=”loggingInterceptor”> Around advice <aop:around pointcut-ref=”daoLayer” method=”intercept”/> </aop:aspect>
  • 27. AOP - Transaction Management public i bli interface T f TransactionManager i M TransactionManager { interface public void enter(); public void abort(); p public void leave(); (); @Aspect Transaction management public interface TransactionInterceptor implemented with { around advice @Around( ”execution( public no.uio.inf5750.dao.*.*(..) )” ) // In-line pointcut public void intercept( ProceedingJoinPoint joinPoint ) { transactionManager.enter(); g (); Enters transaction before method invocation try { joinPoint.proceed(); } Aborts and rolls back catch ( Throwable t ) transaction if method fails { transactionManager.abort(); throw t; } Leaves transaction if method completes norm. transactionManager.leave();
  • 28. @AspectJ or Schema based? Schema-based? • Advantages of schema style – Can be used with any JDK level – Clearer which aspects are present in the system • Advantages of @AspectJ style – One single unit where information is encapsulated for an aspect – Possible to combine named pointcuts – Can be understood by AspectJ – easy to migrate later
  • 29. Summary • Key components in AOP are aspect, pointcut, join point, and advice • AOP lets you encapsulate functionality that affects multiple classes in an interceptor • Advantages of AOP: – Promotes separation of concern – Promotes code reuse and modularization – Promotes loosely coupled design
  • 30. References • The Spring reference documentation - Chapter 6 – www.springframework.org • AOP example code – www ifi uio no/INF5750/h07/undervisningsplan xml www.ifi.uio.no/INF5750/h07/undervisningsplan.xml