Aspect oriented programming_with_spring


Published on

Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Aspect oriented programming_with_spring

  1. 1. Aspect Oriented Programming with Spring
  2. 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. 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 ) { ”Executing saveEvent( Event ) with argument + ” event.toString() ); Logging method executions Session session = sessionManager.getCurrentSession(); return (Integer) event ); } public Event getEvent( Integer id ) { ”Executing getEvent( int )” ); Session session = sessionManager.getCurrentSession(); return (Event) session.get( Event.class, id ); }
  4. 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. 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. 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. 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. 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
  9. 9. Spring overview
  10. 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. 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. 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="" xmlns:xsi="" xmlns:aop="" xsi:schemaLocation=""> <aop:aspectj-autoproxy/>
  13. 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. 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. 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. 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. 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. ”Executing ” + joinPoint.getSignature().toShortString() ); }
  18. 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 ”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 { ”Execution failed ” + joinPoint.getSignature().toShortString() ); @AfterThrowing. }
  19. 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 ”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; } ”Successfully executed ” + joinPoint.getSignature().toShortString() ); }
  20. 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 ) { ”Executing ” + joinPoint.getSignature().toShortString() + Will restrict matching ” with argument ” + object.toString() ); to methods declaring } at least one parameter
  21. 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 ”Executed ” + joinPoint.getSignature().toShortString() + to methods returning a ” with return value ” + object.toString() ); } value of specified type
  22. 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. 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. 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. 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. 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. 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. 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. 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. 30. References • The Spring reference documentation - Chapter 6 – • AOP example code – www ifi uio no/INF5750/h07/undervisningsplan xml
  1. A particular slide catching your eye?

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