470 likes | 597 Views
Presentation By ANUSHA N. Aspect Oriented Programming. AGENDA. Introduction To AOP AOP Concepts Aspect Joinpoint Advice Pointcuts Target Object Weaving. What Is AOP.
E N D
Presentation By ANUSHA N Aspect Oriented Programming 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. Cross cutting concerns Withdrawmethod Deposit method • 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 Adlux Consultancy Services Pvt Ltd
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
Could we not write these cross cutting concerns as functions and call? • 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 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
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 • Action taken at a particular joinpoint is called Advice. • The following are the different types of advices available in Spring. • Before Advice • After Advice • Throws Advice • Around 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 Controlwithin 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
POINTCUTS Adlux Consultancy Services Pvt Ltd
Pointcuts • Point Cutsdefine 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
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" class="org.springframework. aop. support.NameMatchMethodPointcutAdvisor"> <property name="mappedName"> <value>get*</value> </property> (OR) <property name=“mappedNames”> <list> <value>get*</value> <value>set*</value> <value>method1</value> </list> </property> <property name="advice"> <ref bean=“sampleAdvice "/> </property> </bean> Adlux Consultancy Services Pvt Ltd
Pointcuts <bean id=“myTargetClass" class=“MyClass“/> <bean id=“sampleAdvice" class=“MySampleAdvice“/> <bean id=“proxy“ class=“org.springframework.aop.framework.ProxyFactoryBean“> <property name="proxyInterfaces“> <value>MyInterface</value> </property> <property name="target"> <ref bean=“myTargetClass "/> </property> <property name="interceptorNames"> <value>getMethodsAdvisor </value> </property> </bean> </beans> Adlux Consultancy Services Pvt Ltd
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="regExpAdvisor“ class="org.springframework.aop. support.RegexpMethodPointcutAdvisor "> <property name=“advice"> <ref bean="sampleAdvice"/> </property> <property name=“patterns”> <list> <value>m.*1</value> <value>.*method.*</value> </list> </property> </bean> Adlux Consultancy Services Pvt Ltd
Pointcuts <bean id=“myTargetClass" class=“MyClass“/> <bean id=“sampleAdvice" class=“MySampleAdvice“/> <bean id="person" 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> Adlux Consultancy Services Pvt Ltd
Pointcuts Adlux Consultancy Services Pvt Ltd
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="dynamicPointcut“ class="org.springframework. aop. support.ControlFlowPointcut"> <constructor-arg> <value>javax.servlet.http.HttpServlet</value> </constructor-arg> </bean> <bean id="dynamicAdvisor" class="org.springframework. aop.support.DefaultPointcutAdvisor"> <property name="advice"> <ref bean=" sampleAdvice "/> </property> <property name="pointcut"> <ref bean="dynamicPointcut"/> </property> </bean> Adlux Consultancy Services Pvt Ltd
Pointcuts <bean id=“myTargetClass" class=“MyClass“/> <bean id=“sampleAdvice" class=“MySampleAdvice“/> <bean id="person" 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> Adlux Consultancy Services Pvt Ltd
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 Sample ProxyFactoryBean Configuration <bean id=“sampleProxy" class=“org.springframework.aop. framework.ProxyFactoryBean“> <property name="proxyInterfaces“> <value>SampleInterface</value> </property> <property name="target"> <ref bean="sampleTarget"/> </property> <property name="interceptorNames"> <value>sampleAdvice</value> </property> </bean> <bean id=“sampleTarget" class=“MySampleTarget“/> <bean id=“sampleAdvice" class=“MySampleAdvice“/> Adlux Consultancy Services Pvt Ltd
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="org.springframework.aop. framework.autoproxy.BeanNameAutoProxyCreator"> <property name="beanNames"> <list><value>*Service</value></list> </property> <property name="interceptorNames"> <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="advisor" class="org.springframework.aop.support. RegexpMethodPointcutAdvisor"> <property name="advice"> <bean class="performanceThresholdInterceptor"/> </property> <property name="pattern"> <value>.+Service\..+</value> </property> </bean> <bean id="autoProxyCreator” class="org.springframework.aop. framework.autoproxy.DefaultAdvisorAutoProxyCreator"/> <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
THANK YOU Adlux Consultancy Services Pvt Ltd