Spring aop concepts


Published on

Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects. (Such concerns are often termed crosscutting concerns in AOP literature.)
One of the key components of Spring is the AOP framework. While the Spring IoC container does not depend on AOP, meaning you do not need to use AOP if you don't want to, AOP complements Spring IoC to provide a very capable middleware solution.

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Spring aop concepts

  1. 1. By: Rushi B Shah
  2. 2.  What is AOP?  Why it is required?  AOP Terminology  AspectJ as an AOP framework  AspectJ Annotation Syntax  Different types of Advices and its Implementation
  3. 3.  Concern is any use case/interest area present in application  Core/Primary concern is the core business functionality  Cross-cutting/Secondary concern like authentication, logging, exception handling  In OOP, we have tight coupling between core and crosscutting concerns  AOP introduces loose coupling between core and crosscutting concerns  AOP is nothing but modularization of concerns
  4. 4.      AOP helps overcome system-level coding i.e. logging, transaction mgmt, security mgmt, caching, internationalization etc. by modularizing cross-cutting concerns AOP addresses each aspect separately thereby minimizing coupling and duplication in code It promotes code reuse Developers can concentrate on one aspect at a time Make easier to add newer functionality's by adding new aspects and weaving rules and subsequently regenerating the final code.
  5. 5.           Concern: A direct or indirect functionality to be addressed in the application Aspect: It is a module that encapsulates a concern Join Point: A point in the execution of a program like execution of a method or handling of an exception It denotes the “where” part Advice: Action to be taken by the Aspect when a particular Join Point is reached • It denotes the “what” part Pointcut: It is a predicate that matches Join Point. • It is an expression which defines which methods will be affected by the Advice • It denotes the “when” part Target Object: The object being advised by one or more aspects Weaving: Linking aspects to other application types or objects to create advised objects AOP Proxy: An object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on) Advisor: An Advisor is like a small self-contained aspect that has a single piece of advice.
  6. 6.      Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception). After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception. After throwing advice: Advice to be executed if a method exits by throwing an exception. After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return). Around advice: Advice that surrounds a join point such as a method invocation
  7. 7.       Designator can have values like execution, within, this. Return type can be * to match any return type Fully-qualified path means path with package hierarchy (optional) Method name can use * to match any name Parameters can have values like “()” no param, “*” any one parameter, “..” (Any no of parameters) Designator({return-type} {fully-qualified path} {methodname} {parameters} {throws exception} )
  8. 8.    Spring AOP interprets AspectJ annotations at run-time by a library provided by AspectJ framework. Spring supports only method execution join points for the beans in its IoC container. So if you use join points beyond this scope in Spring, it will give you IllegalArgumentsException at runtime.
  9. 9. Type Kinded Dynamic Scope Syntax Meaning the method name execution(* set*(*)) matches a method-execution join point, if starts with "set" and there is exactly one argument of any type and any one return type this(Point) within(com.company.*) pointcut set() : execution(* Composed set*(*) ) && this(Point) && within(com.company.*); matches when the currently executing object is an instance of class Point. Note that the unqualified name of a class can be used via Java's normal type lookup. matches any join point in any type in the com.company package. The * is one form of the wildcards that can be used to match many things with one signature. matches a method-execution join point, if the method name starts with "set" and any one return type and this is an instance of type Point in the com.company package.
  10. 10.  Using AspectJ Annotations Using AspectJ XML Configuration(Schema based approach) In this scenario, an <aop:config> element can contain pointcut, advisor, and aspect elements (note: They must be declared in the same order). 
  11. 11. import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class BeforeExample { @Before("execution(*com.xyz.myapp.dao.*.*(..))") public void doAccessCheck() { // method definition } }
  12. 12. <aop:aspectj-autoproxy /> <bean id="customerBo“ class="com.mkyong.customer.bo.impl.CustomerBoImpl"/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <!-- @Before --> <aop:pointcut id="pointCutBefore“ expression="execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))" /> <aop:before method="logBefore" pointcutref="pointCutBefore" /> </aop:config>
  13. 13.     import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.AfterReturning; @Aspect public class AfterReturningExample {  @AfterReturning(pointcut="com.xyz.myapp.SystemArchitecture .dataAccessOperation()”, returning=“retVal”)  public void doAccessCheck() {  // method definition  }  }
  14. 14. <aop:aspectj-autoproxy /> <bean id="customerBo“ class="com.mkyong.customer.bo.impl.CustomerBoImpl"/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <!-- @AfterReturning --> <aop:pointcut id="pointCutAfterReturning“ expression="execution(* com.mkyong.customer.bo.CustomerBo.addCustomerReturnValu e(..))" /> <aop:after-returning method="logAfterReturning" returning="result" pointcut-ref="pointCutAfterReturning" /> </aop:config>
  15. 15. import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.AfterThrowing; @Aspect public class AfterThrowingExample { @AfterThrowing(pointcut="com.xyz.myapp.SystemArchi tecture.dataAccessOperation()", throwing="ex") public void doRecoveryActions(DataAccessException ex) { // method definition } }
  16. 16. <aop:aspectj-autoproxy /> <bean id="customerBo“ class="com.mkyong.customer.bo.impl.CustomerBoImpl"/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <!-- @AfterThrowing --> <aop:pointcut id="pointCutAfterThrowing“ expression="execution(* com.mkyong.customer.bo.CustomerBo.addCustomerThrowExcepti on(..))" /> <aop:after-throwing method="logAfterThrowing" throwing="error" pointcut-ref="pointCutAfterThrowing" /> </aop:config>
  17. 17. import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.After; @Aspect public class AfterFinallyExample { @After("com.xyz.myapp.SystemArchitecture.d ataAccessOperation()") public void doReleaseLock() { // method definition } }
  18. 18. <aop:aspectj-autoproxy /> <bean id="customerBo“ class="com.mkyong.customer.bo.impl.CustomerBoImpl"/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <!-- @After --> <aop:pointcut id="pointCutAfter“ expression="execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))" /> <aop:after method="logAfter" pointcut-ref="pointCutAfter" /> </aop:aspect> </aop:config>
  19. 19. import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.ProceedingJoinPoint; @Aspect public class AroundExample { @Around("com.xyz.myapp.SystemArchitecture.busi nessService()") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { // just like before advice Object retVal = pjp.proceed(); //original method call // just like after returning advice return retVal; } }
  20. 20. <aop:aspectj-autoproxy /> <bean id="customerBo“ class="com.mkyong.customer.bo.impl.CustomerBoImpl"/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <aop:pointcut id="pointCutAround“ expression="execution(* com.mkyong.customer.bo.CustomerBo.addCustomerAround (..))" /> <aop:around method="logAround" pointcutref="pointCutAround" /> </aop:aspect> </aop:config>
  21. 21. @Aspect public class LoggingAspect { @Before("execution(*com.mkyong.customer.bo.Cu stomerBo.addCustomer(..))") public void logBefore(JoinPoint joinPoint) { //method definition } } @Aspect public class OtherAspect { @Before(LoggingAspect.logBefore()) //AspectClassName. methodname public void otherMethod(JoinPoint joinpoint) { //method definition} }
  22. 22.        If you apply all the five types of advices on a single method, then the execution order irrespective of its implementation(annotation-based or XML configuration based) will be : 1) Before Advice 2) Before Proceed part of Around Advice 3) Actual method call execution 4) After Advice 5) After Returning Advice 6) After Proceed part of Around Advice
  23. 23.        Spring AOP or full AspectJ? If you only need to advise the execution of operations on Spring beans, then Spring AOP is the right choice. If you need to advise objects not managed by the Spring container (such as domain objects typically), then you will need to use AspectJ. You will also need to use AspectJ if you wish to advise join points other than simple method executions (for example, field get or set join points, and so on). @AspectJ or XML for Spring AOP? When using AOP as a tool to configure enterprise services then XML can be a good choice because it is clearer from your configuration what aspects are present in the system. While using XML syntax, the aspect implementation is split across XML Configuration file(containing pointcut expression) and backing bean class(containing advice implementation). But in @AspectJ syntax, both of these implementation remain in a single aspect class and it is easy to combine two pointcut expression with it.
  24. 24. If the target object to be proxied implements at least one interface then a JDK dynamic proxy will be used. All of the interfaces implemented by the target type will be proxied.  If the target object does not implement any interfaces then a CGLIB proxy will be created.  If you want to force the use of CGLIB proxying ,there are some issues to consider: i) final methods cannot be advised, as they cannot be overridden. ii) You will need the CGLIB 2 binaries on your classpath, whereas dynamic proxies are available with the JDK. Spring will automatically warn you when it needs CGLIB and the CGLIB library classes are not found on the classpath. 
  25. 25. Thank You