Tuesday, May 10, 2011

Spring Aop

  1. Spring AOP
  2. OO Design is good but…
    • The oop languages makes the code design more reusable and compact.
    • But sometimes it makes the code scattered in number of modules.
    • More code plumbing has to be done…
    • Example : adding message logging in each of class methods makes the logging code scattered in number of methods and classes.
    • This makes code maintenance and updation a tedious work.
  3. AOP is the solution…
    • ‘ Aspect Oriented Programming(AOP)’ addresses these issues.
    • Instead of adding the logging code in each of the methods, you delegate the logging functionality ( concern ) across number of methods to an aop container and specify which methods require logging applied.
    • The container will call the logging aspect of the code when the methods are invoked on the proxy object returned by the Container.
  4. AOP
    • Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. In addition to classes, AOP gives you aspects .
    • Aspects enable modularization of concerns (required additional business logic) such as transaction management that cut across multiple types and objects. (Such concerns are often termed crosscutting concerns.)
  5. AOP In JSP Engine Register.jsp (throws Exception) Login.jsp (throws SQLException) Update.jsp (throws UserException) request request request Handler.jsp <%=exception%> <%@page errorPage=“Handler.jsp”%> <%@page errorPage=“Handler.jsp”%> <%@page errorPage=“Handler.jsp”%> <%@page isErrorPage=“true”%> JSP Engine
  6. We are using AOP…
    • For exception handling in the JSP pages,instead of writing individual ‘try-catch’ blocks in each jsp we make a common exception handler jsp and specify in each jsp the ref. of this common handler by using isErrorPage and errorPage attributes in page directive tag.
    • When any of the jsp page generates the exception it is forwarded to common handler page by the web container.
    • Another example is specifying Filters to be invoked transparently before Servlet invocations in java web applications.
  7. AOP advantages
    • Complements OO programming.
    • Clean and modular code without additional code plumbing.
    • Aspects can be added or removed as needed without changing the code.
    • The business object code is not tied to specific API or framework
  8. Some AOP terminologies
    • Concern - The required functionality.(logging,tracing etc.)
    • Aspect – A modularization of a concern that cuts across multiple objects and methods.
    • Join point – A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.
    • Advice – the block of code that runs based on the pointcut definition
  9. AOP Terminologies
    • Pointcut – A predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name).
    • Advisor - references the advice and the pointcut.
    • Target object : Object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.
    • AOP proxy : An object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on).
  10. More aop terms..
    • Introduction : Declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any proxied object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching.
    • Weaving – Linking aspects with other application types or objects to create an advised object can be done at runtime or compile time. Which inserts the advice (crosscutting concerns) into the code. Spring provides run time weaving.
  11. Cross cutting concerns
    • Concerns applied across number of classes are called as cross cutting concerns.
  12. Spring AOP support
    • AOP Framework that builds on the aopalliance interfaces.
    • Aspects are coded with pure Java code.
    • Spring aspects can be configured using its own IoC container.
      • Objects obtained from the IoC container can be transparently advised based on configuration
    • Spring AOP has built in aspects such as providing transaction management, performance monitoring and more for your beans.
    • Spring supports proxy based AOP to bean methods.
  13. Spring Advices
    • Spring AOP supports the following advices:
      • Before advice : (Advice is applied before method is executed)
      • After returning advice : (Advice is applied after method is returned normally without throwing any Exceptions)
      • After throwing advice : Advice to be executed if a method exits by throwing an exception.
      • Around advice : Advice that surrounds a join point such as a method invocation. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.
  14. Simple AOP Weaving
  15. Applying the Advices..
    • Aspects are weaved together at runtime. AspectJ uses compile time weaving.
    • Spring AOP also includes advisors that contain advice and pointcut filtering.
    • IoC + AOP is a great combination that Makes the code non-invasive
  16. Using Spring AOP
    • To provide declarative enterprise services, especially as a replacement for EJB declarative services such as declarative transaction management .
    • Providing declarative linking of web application components.
    • To allow users to implement custom aspects, complementing their use of OOP with AOP.
  17. Spring AOP Features
    • Spring AOP does not need to control the class loader hierarchy, and is thus suitable for use in a J2EE web container or application server or in a desktop application.
    • Spring AOP currently supports only method execution join points.
    • The aspects can be programmatically or declaratively configured through xml.
    • The aspects can be configured with jdk1.5 annotations features.
  18. Method Interceptor
    • MethodInterceptor used to implement for Advices/Interceptors on methods.
      • public Object invoke(MethodInvocation invocation) throws Throwable
  19. Spring Advice interfaces
    • BeforeAdvice
      • Public void before(Method m, Object[] args, Object target) throws Throwable;
    • ThrowsAdvice
      • public void afterThrowing(Method m, Object[ ] args, Object target, Throwable ex);
    • AfterReturningAdvice
      • Public void afterReturning(Object returnValue, Method m, Object[ ] args, Object target) throws Throwable;
  20. Defining PointCut
    • package org.springframework.aop;
    • public interface Pointcut
    • {
    • ClassFilter getClassFilter();
    • MethodMatcher getMethodMatcher();
    • }
  21. ClassFilter
    • Public boolean matches ( Class  clazz);
    • Decides whether the specified pointcut should be applied to the given interface or target class objects.
    • Filter that restricts matching of a pointcut or introduction to a given set of target classes.
    • Can be used as part of a pointcut, or for the entire targeting of an IntroductionAdvice
  22. MethodMatcher
    • Part of a Pointcut. Checks whether the target method is eligible for advice.
    • A MethodMatcher may be evaluated statically or at runtime (dynamically).
    • Static matching involves method and (possibly) method attributes. Dynamic matching also makes arguments for a particular call available, and any effects of running previous advice applying to the joinpoint
  23. Apply MethodMatcher
    • If an implementation class returns false in its isRuntime() method, evaluation can be performed statically, and the result will be the same for all invocations of this method, whatever their arguments.
    • If the isRuntime() method returns false, the 3-arg matches() method will never be invoked.
  24. PointCut Usage
    • Used to target advices to particular classes and methods.
    • Spring's pointcut model enables pointcut reuse independent of advice types.
    • It's possible to target different advices using the same pointcut.
    • ClassFilter and MethodMatcher are interfaces which are used to restrict the pointcut to a given set of target classes and used to test matching of a particular method against a given method, respectively.
  25. Operations on pointcuts
    • Spring supports two operations on pointcuts:
      • Union means the methods that either pointcut matches and is usually more useful.
      • Intersection means the methods that both pointcuts match.
    • Pointcuts can be composed using the static methods in the org.springframework.aop.support.Pointcuts class, or using the ComposablePointcut class in the same package.
  26. Static pointcuts
    • Static pointcuts are based on method and target class, and cannot take into account the method's arguments.
    • Static pointcuts are sufficient for most usage. It's possible for Spring to evaluate a static pointcut only once, when a method is first invoked: after that, there is no need to evaluate the pointcut again with each method invocation.
  27. Dynamic pointcuts
    • These take into account method arguments , as well as static information. This means that they must be evaluated with every method invocation and the result cannot be cached, as arguments will vary.
    • Example is the control flow pointcut.
    • Control flow pointcuts are specified using the ControlFlowPointcut class.
    • Spring provides useful pointcut super classes to help you to implement your own pointcuts.
  28. Spring Advisor
    • Spring has defined Advisor interface for combining advice and pointcut.
    • This is the base interface holding AOP advice (action to take at a joinpoint) and a filter determining the applicability of the advice (such as a pointcut).
    • This allows for common support for different types of advices.
    • Spring AOP is based around around advice delivered via method interception, compliant with the AOP Alliance interception API.
    • The Advisor interface allows support for different types of advice, such as before and after advice, which need not be implemented using interception.
  29. Advisor Implementation
    • Spring has a RegexpMethodPointcutAdvisor , that allows us to also reference an Advice (Advice can be an interceptor, before advice, throws advice etc.)
    • This advice is mapped to specific matching methods.
    • DefaultIntroductionAdvisor applies by default to any class.
    • DefaultPointcutAdvisor :can be used with any pointcut and advice type, except for introductions.
    • DynamicMethodMatcherPointcutAdvisor : super class for classes as Advisors that are also dynamic pointcuts.
    • NameMatchMethodPointcutAdvisor :class for name-match method pointcuts that hold an Advice, making them an Advisor.
    • StaticMethodMatcherPointcutAdvisor :superclass for Advisors that are also static pointcuts.
  30. Advisor declaration
    • <bean id=“tg“
    • class=&quot;org..aop.support. RegexpMethodPointcutAdvisor &quot;>
    • <property name=&quot;advice&quot;>
    • <ref local=&quot;beanAdvice&quot;/>
    • </property>
    • <property name=&quot;patterns&quot;>
      • <list>
      • <value>.*set.*</value>
      • <value>.*Calculate</value>
      • </list>
    • </property>
    • </bean>
  31. Spring PointCut Classes
    • ComposablePointcut : class for building up pointcuts.
    • ControlFlowPointcut :Pointcut and method matcher for use in simple cflow-style pointcut.
    • DynamicMethodMatcherPointcut :Base class when we want to force subclasses to implement MethodMatcher interface, but subclasses will want to be pointcuts. The getClassFilter() method can be overriden to customize ClassFilter behaviour as well.
    • StaticMethodMatcherPointcut : superclass when we want to force subclasses to implement the MethodMatcher interface, but subclasses will want to be pointcuts.

No comments: