• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Spring AOP
 

Spring AOP

on

  • 3,252 views

Basics of Spring AOP for spring learners

Basics of Spring AOP for spring learners

Statistics

Views

Total Views
3,252
Views on SlideShare
3,245
Embed Views
7

Actions

Likes
6
Downloads
239
Comments
0

2 Embeds 7

http://www.slideshare.net 6
http://webcache.googleusercontent.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Spring AOP Spring AOP Presentation Transcript

    • Adlux Consultancy Services Pvt Ltd
    • AGENDA
      • Introduction To AOP
      • AOP Concepts
          • Aspect
          • Joinpoint
          • Advice
          • Pointcuts
          • Target Object
          • Weaving
      Adlux Consultancy Services Pvt Ltd
    • What Is AOP
      • Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns
      • It is often defined as a programming technique that promotes separation of crosscutting concerns with in a software system.
      • concerns :
      • A concern is a particular issue, concept, or area of interest for an application: typically, a goal the application must meet.
      Adlux Consultancy Services Pvt Ltd
    • Cross-cutting concerns
      • The systems or concerns that tend to cut across multiple components in a system are referred as Cross-cutting concerns
      • System wide concerns that span multiple modules.
      • Cuts across the typical division of responsibility.
      • Examples such as
        • Transaction Management
        • Security
        • Logging
      Adlux Consultancy Services Pvt Ltd
    • Cross Cutting Concerns in OOP Approach
        • OOP creates a coupling between core and crosscutting concerns. This causes
          • Leads to duplicated code.
          • Hard to maintain code.
          • Hard to use code.
      Adlux Consultancy Services Pvt Ltd
      • Transaction Management
      • Logging
      • Checking for the Privileged User
      • Actual Withdraw Logic
      • comes here
      • Transaction Management
      • Logging
      • Checking for the Privileged User
      • Actual Deposit Logic
      • comes here
      Withdraw method Deposit method Cross cutting concerns
      • Public class Account
      • {
      • public void deposit() {
      • // Transaction Management
      • // Logging
      • // Checking for the Privileged User
      • // Actual Deposit Logic comes here
      • }
      • public void withdraw() {
      • // Transaction Management
      • // Logging
      • // Checking for the Privileged User
      • // Actual Withdraw Logic comes here
      • }
      • }
      • AOP calls this kind of logic that cross-cuts the existing business logic as Cross-Cutting Concerns .
      Adlux Consultancy Services Pvt Ltd
        • Results in code permeating though the system at various places – hard to maintain
        • Harder to express concerns this way
        • You have to modify your code to invoke these concerns
          • requires understanding at each level
      Could we not write these cross cutting concerns as functions and call? Adlux Consultancy Services Pvt Ltd
    • If we use AOP
          • Spring AOP will take care of calling concerns, we just need to declare about concerns once in configuration file.
            • You can focus on the concerns at one place
            • Easier to add and remove concerns
            • Easier to modify or fine tune concerns
            • Easier to understand
            • Efficient to implement
            • More efficient
      Adlux Consultancy Services Pvt Ltd
    • AOP Terminology
      • Joinpoint
      • A point during the execution of a program, such as the execution
      • of a method or the handling of an exception.
      • We can insert additional logic at Joinpoint's.
      • In Spring AOP, a join point always represents a method execution.
      • Advice
      • Action taken at a particular joinpoint is called Advice.
      • PointCut
      • A declarative condition that identifies for which joinpoint, the advices should fire.
      • Aspect:
      • An aspect is a modularization of a crosscutting concern; the gathering together of code that might otherwise have been scattered. It is termed as the combination of the point-cut and the advice .
      Adlux Consultancy Services Pvt Ltd
    • AOP vs OOP Adlux Consultancy Services Pvt Ltd Object Oriented Aspect Oriented Class – code unit that encapsulates methods and attributes. Aspect – code unit that encapsulates pointcuts, advice, and attributes. Method signatures – define the entry points for the execution of method bodies. Pointcut – define the set of entry points (triggers) in which advice is executed. Method bodies – implementations of the primary concerns. Advice – implementations of the cross cutting concerns. Compiler – converts source code into object code. Weaver – instruments code (source or object) with advice.
    • AOP History
      • Spring implements the AOP Alliance interception interfaces .
      • Emerged about 10 years ago from different research efforts studying the separation of concerns in software
      • Supported in industry today by IBM, BEA,
      • AOP support is available for Java, C++, C, PHP,
      • AspectJ, AspectC++, AspectC, AOPHP,
      Adlux Consultancy Services Pvt Ltd
    • Advice Adlux Consultancy Services Pvt Ltd
    • Advice Adlux Consultancy Services Pvt Ltd
    • Advice
      • Before Advice :
      • It is used to intercept before the method execution starts.
      • public class Authentication extends BeforeAdvice
      • {
      • public void before(Method method, Object[] args, Object target) throws Throwable
      • {
      • if (args[0] instanceof User)
      • {
      • User user = (User)args[0];
      • // Authenticate if he/she is the right user
      • }
      Adlux Consultancy Services Pvt Ltd
    • Advice
      • From the above code
      • before() method will be called before the execution of method call.
      • method object represents target method to be invoked.
      • Object[] args refers to the various arguments that are passed on to the method.
      Adlux Consultancy Services Pvt Ltd
    • Advice
      • After Advice
      • It will be useful if some logic has to be executed before Returning the Control within a method execution.
      • public class CleanUpOperation implements AfterReturningAdvice
      • public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable
      • {
      • // Clean up session and user information.
      • }
      • }
      Adlux Consultancy Services Pvt Ltd
    • Advice
      • From the above code
      • afterReturning() will be called once the method returns normal execution.
      • If some exception happens in the method execution the afterReturning() method will never be called.
      • Throws Advice :
      • some kind of exception happens during the execution of a method, then to handle the exception properly.
      Adlux Consultancy Services Pvt Ltd
    • Advice
      • public class DeleteFile implements ThrowsAdvice
      • {
      • public void afterThrowing(Method method, Object[] args, Object target, IOException exception)
      • {
      • String targetFileName = (String)args[2];
      • // Code to delete the target file.
      • }
      • }
      • From the above code
      • afterThrowing() method will be called when an Exception, that too of type IOException is thrown
      Adlux Consultancy Services Pvt Ltd
    • Advice
      • Around Advice :
      • Advice that surrounds a joinpoint such as a method invocation.
      • They are responsible for choosing whether to proceed to the joinpoint executing by returning their own return value or throwing an exception.
      • Intercepts the calls to the target method.
      • this Advice provides finer control whether the target method has to be called or not.
      Adlux Consultancy Services Pvt Ltd
    • Advice
      • public class ValidateArguments implements MethodInterceptor
      • public Object invoke(MethodInvocation invocation) throws Throwable
      • Object arguments [] = invocation.getArguments();
      • if ((arguments[0] instanceof Parent) && (arguments[1] instanceof Child) )
      • {
      • Object returnValue = invocation.proceed();
      • return returnValue;
      • }
      • throw new Exception ("Arguments are of wrong type"); 
      • }
      • }
      Adlux Consultancy Services Pvt Ltd
    • Advice
      • From the above code
      • It is important to make a call to MethodInvocation.proceed(), if we are happy with the arguments validation, else the target method will never gets invoked.
      Adlux Consultancy Services Pvt Ltd
    • Adlux Consultancy Services Pvt Ltd
    • Pointcuts
      • Point Cuts define where exactly the Advices have to be applied in various Join Points i.e Set of Joinpoints specifying when an advice should fire.
      • Generally they act as Filters for the application of various Advices into the real implementation.
      • Each built-in Pointcuts has an advisor
      • PointcutAdvisor=Pointcut + Advice
      Adlux Consultancy Services Pvt Ltd
    • Adlux Consultancy Services Pvt Ltd
    • Pointcuts
      • public interface Pointcut
      • {
      • ClassFilter getClassFilter();
      • MethodMatcher getMethodMatcher();
      • }
      • public interface ClassFilter
      • {
      • boolean matches(Class clazz);
      • }
      • public interface MethodMatcher
      • {
      • boolean matches(Method m,Class targetClass);
      • boolean isRuntime();
      • boolean matches(Method m,Class targetClass,Object[] args);
      • }
      Adlux Consultancy Services Pvt Ltd
    • Pointcuts
      • Spring defines two types of Point Cuts namely the
      • Static and Dynamic Point Cuts.
      • Static Pointcuts
      • NameMatchMethod Pointcut
      • Regular Expression Pointcut
      • NameMatchMethod Pointcut :
      • Here the name of the methods that are to be given advices can be directly mentioned in the Configuration File.
      Adlux Consultancy Services Pvt Ltd
    • Pointcuts
      • MyInterface.java
      • public interface MyInterface
      • { public void setMessage(String msg);
      • public void method1();
      • public void method2();
      • public void getMethod1();
      • public void getMethod2();
      • }
      • MyClass.java
      • public class MyClass implements MyInterface
      • private String message;
      • public void setMessage(String msg)
      • {
      • this.message=msg;
      • }
      • public void method1(){}
      • public void method2(){} 
      • public void getMethod1() {}
      • public void getMethod2(){}
      • }
      Adlux Consultancy Services Pvt Ltd
    • Pointcuts
      • ApplicationContext.xml
      • <beans>
      • <bean id=“getMethodsAdvisor&quot; class=&quot; org.springframework. aop. support.NameMatchMethodPointcutAdvisor &quot;>
      • <property name=&quot;mappedName&quot;>
      • <value>get*</value>
        • </property>
        • (OR)
        • <property name=“mappedNames”>
        • <list> <value>get*</value>
        • <value>set*</value>
        • <value>method1</value>
        • </list>
        • </property>
      • <property name=&quot;advice&quot;>
      • <ref bean=“sampleAdvice &quot;/>
      • </property>
      • </bean>
      Adlux Consultancy Services Pvt Ltd
    • Pointcuts Adlux Consultancy Services Pvt Ltd <bean id=“myTargetClass&quot; class=“MyClass“/> <bean id=“sampleAdvice&quot; class=“MySampleAdvice“/> <bean id=“proxy“ class=“ org.springframework.aop.framework.ProxyFactoryBean “> <property name=&quot;proxyInterfaces“> <value>MyInterface</value> </property> <property name=&quot;target&quot;> <ref bean=“myTargetClass &quot;/> </property> <property name=&quot;interceptorNames&quot;> <value> getMethodsAdvisor </value> </property> </bean> </beans>
    • Pointcuts
      • get* tells that all method names starting with the method name get will be given Advices .
      • If we want all the methods in the MyClass to be adviced, then the 'value' tag should be given '*' meaning all the methods in the Class.
      Adlux Consultancy Services Pvt Ltd
    • Pointcuts
      • Regular Expression Pointcut
      • It is used if you want to match the name of the methods in the Class based on Regular Expression.
      • Spring distribution already comes with two supported flavors of Regular Expression namely Perl Regular Expression and Jdk Regular Expression .
      Adlux Consultancy Services Pvt Ltd
    • Pointcuts
      • MyInterface.java
      • public interface MyInterface
      • {
      • public void method1();
      • public void method11();
      • public void method2();
      • public void getMethod1();
      • public void getMethod2();
      • }
      • MyClass.java
      • public class MyClass implements MyInterface
      • public void method1(){}
      • public void method11(){}
      • public void method2(){} 
      • public void getMethod1(){} 
      • public void getMethod2(){}
      • }
      Adlux Consultancy Services Pvt Ltd
    • Pointcuts
      • ApplicationContext.xml
      • <bean id=&quot;regExpAdvisor“ class=&quot; org.springframework.aop. support.RegexpMethodPointcutAdvisor &quot;>
      • <property name=“advice&quot;>
      • <ref bean=&quot;sampleAdvice&quot;/>
      • </property>
      • <property name=“patterns”>
      • <list>
      • <value>m.*1</value>
      • <value>.*method.*</value>
      • </list>
      • </property>
      • </bean>
      Adlux Consultancy Services Pvt Ltd
    • Adlux Consultancy Services Pvt Ltd <bean id=“myTargetClass&quot; class=“MyClass“/> <bean id=“sampleAdvice&quot; class=“MySampleAdvice“/> <bean id=&quot;person&quot; class=“ org.springframework.aop. framework.ProxyFactoryBean “> <property name=“proxyInterfaces” > <value>MyInterface</value> </property> <property name=“target”> <ref bean=“myTargetClass”/> </property> <property name=“interceptorNames”> <value> regExpAdvisor </value> </property> </bean> Pointcuts
    • Pointcuts Adlux Consultancy Services Pvt Ltd Symbol Description . Matches Any Single Character + Mathches the Preceding Character one or more times * Mathches the Preceding Character Zero or more times / Escapes any Regular Expression Symbols
    • Pointcuts
      • Dynamic Pointcuts :
      • However, there may be some cases where your pointcuts will need to evaluate runtime attributes.
      • Spring provides one built-in dynamic pointcut: ControlFlowPointcut.
      • This pointcut matches based on information about the current thread’s call stack.
      • That is, it can be configured to return true only if a particular method or class is found in the current thread’s stack of execution .
      Adlux Consultancy Services Pvt Ltd
    • Pointcuts
      • Dynamic Pointcut Configuration
      • <bean id=&quot;dynamicPointcut“ class=&quot; org.springframework. aop. support.ControlFlowPointcut&quot;>
      • <constructor-arg>
      • <value>javax.servlet.http.HttpServlet</value>
      • </constructor-arg>
      • </bean>
      • <bean id=&quot;dynamicAdvisor&quot; class=&quot; org.springframework. aop.support.DefaultPointcutAdvisor &quot;>
      • <property name=&quot;advice&quot;>
      • <ref bean=&quot; sampleAdvice &quot;/>
      • </property>
      • <property name=&quot;pointcut&quot;>
      • <ref bean=&quot;dynamicPointcut&quot;/>
      • </property>
      • </bean>
      Adlux Consultancy Services Pvt Ltd
    • Adlux Consultancy Services Pvt Ltd <bean id=“myTargetClass&quot; class=“MyClass“/> <bean id=“sampleAdvice&quot; class=“MySampleAdvice“/> <bean id=&quot;person&quot; class=“ org.springframework.aop. framework.ProxyFactoryBean “> <property name=“proxyInterfaces” > <value>MyInterface</value> </property> <property name=“target”> <ref bean=“myTargetClass”/> </property> <property name=“interceptorNames”> <value> dynamicAdvisor </value> </property> </bean> Pointcuts
    • Target
      • Object containing the joinpoint .
      • Also referred to as the advised or proxied object .
      • Example
      • <bean id=“ myTargetClass ” class=“sample.MyClass”>
      • <property name=“message”>
      • <value>Welcome to Adlux</value>
      • </property>
      • </bean>
      Adlux Consultancy Services Pvt Ltd
    • Weaving
      • It is the process of applying aspects to a target object to create a new proxied object.
      • The aspects are woven into the target object at the specified joinpoints.
      • different points where weaving can be applied ·  Compile Time
      • ·   Class load Time
      • ·    Runtime
      Adlux Consultancy Services Pvt Ltd
    • AOP Proxy
      • A proxy is the object created after applying advice to the target object.
      • The target object (pre-AOP) & the proxy object
      • (post-AOP) are the same.
      • The object created by the AOP framework that includes the advise.
      • The three properties you will probably use most often are
      • 1 . target
      • 2 . proxyInterfaces
      • 3 . interceptorNames
      Adlux Consultancy Services Pvt Ltd
    • AOP Proxy Adlux Consultancy Services Pvt Ltd Sample ProxyFactoryBean Configuration <bean id=“sampleProxy&quot; class=“org.springframework.aop. framework.ProxyFactoryBean“> <property name=&quot;proxyInterfaces“> <value> SampleInterface </value> </property> <property name=&quot;target&quot;> <ref bean=&quot; sampleTarget &quot;/> </property> <property name=&quot;interceptorNames&quot;> <value> sampleAdvice </value> </property> </bean> <bean id=“sampleTarget&quot; class=“MySampleTarget“/> <bean id=“sampleAdvice&quot; class=“MySampleAdvice“/>
    • AOP Proxy
      • Spring will create a proxy using a JDK dynamic proxy or a CGLIB proxy.
      • First providing the ProxyFactory with all the aspects that you want to be woven into the proxy.
      • You typically use ProxyFactoryBean class to provide declarative proxy creation.
      • Different types of AutoProxying
      • ·    DefaultAdvisorAutoProxyCreator
      • ·    BeanNameAutoProxyCreator
      Adlux Consultancy Services Pvt Ltd
    • AOP Proxy
      • BeanNameAutoProxyCreator
      • <bean id=“beanNameAutoProxy” class=&quot;org.springframework.aop. framework.autoproxy.BeanNameAutoProxyCreator&quot;>
      • <property name=&quot;beanNames&quot;>
      • <list><value> *Service </value></list>
      • </property>
      • <property name=&quot;interceptorNames&quot;>
      • <value> performanceThresholdInterceptor </value>
      • </property>
      • </bean>
      • <bean id=“performanceThresholdInterceptor” class=“student.performanceThresholdInterceptor”/>
      • <bean id=“studentService” class=“student.StudentService”/>
      • <bean id=“courseService” class=“student.CourseService”/>
      • <bean id=“sampleService” class=“sample.SampleService”/>
      Adlux Consultancy Services Pvt Ltd
    • AOP Proxy
      • 2. DefaultAdvisorAutoProxyCreator
      • <bean id=&quot;advisor&quot; class=&quot; org.springframework.aop.support.
      • RegexpMethodPointcutAdvisor &quot;>
      • <property name=&quot;advice&quot;>
      • <bean class=&quot;performanceThresholdInterceptor&quot;/>
      • </property>
      • <property name=&quot;pattern&quot;>
      • <value> .+Service..+ </value>
      • </property>
      • </bean>
      • <bean id=&quot;autoProxyCreator” class=&quot; org.springframework.aop. framework.autoproxy.DefaultAdvisorAutoProxyCreator &quot;/>
      • <bean id=“studentService” class=“student.StudentService”/>
      • <bean id=“courseService” class=“student.CourseService”/>
      • <bean id=“sampleService” class=“sample.SampleService”/>
      Adlux Consultancy Services Pvt Ltd
    • Spring AOP Capabilities
      • Implemented in pure Java
      • Suitable for use in J2EE container since does not need to control the class loader hierarchy
      • Spring supports interception of methods
      • Does not support field interception
      • Provides classes to represent pointcuts and different advise types
      • Spring advises object at instance, rather than class loader level
      Adlux Consultancy Services Pvt Ltd
    • Adlux Consultancy Services Pvt Ltd