Spring AOP

47
Adlux Consultancy Services Pvt Ltd

description

Basics of Spring AOP for spring learners

Transcript of Spring AOP

Page 1: Spring AOP

Adlux Consultancy Services Pvt Ltd

Page 2: Spring AOP

AGENDA Introduction To AOP AOP Concepts

○ Aspect○ Joinpoint○ Advice○ Pointcuts○ Target Object○ Weaving

Adlux Consultancy Services Pvt Ltd

Page 3: Spring AOP

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

Page 4: Spring AOP

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

Page 5: Spring AOP

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 in OOP ApproachOOP 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

Page 6: Spring AOP

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

Page 7: Spring AOP

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

Could we not write these cross cutting concerns as functions and call?

Page 8: Spring AOP

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

Page 9: Spring AOP

AOP TerminologyJoinpoint 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

Page 10: Spring AOP

AOP vs OOPAOP vs OOP

Object OrientedObject Oriented Aspect OrientedAspect OrientedClass – code unit that Class – code unit that encapsulates methods and encapsulates methods and attributes.attributes.

Aspect – code unit that Aspect – code unit that encapsulates pointcuts, advice, encapsulates pointcuts, advice, and attributes.and attributes.

Method signatures – define Method signatures – define the entry points for the the entry points for the execution of method bodies.execution of method bodies.

Pointcut – define the set of Pointcut – define the set of entry points (triggers) in which entry points (triggers) in which advice is executed.advice is executed.

Method bodies – Method bodies – implementations of the implementations of the primary concerns.primary concerns.

Advice – implementations of Advice – implementations of the cross cutting concerns.the cross cutting concerns.

Compiler – converts source Compiler – converts source code into object code.code into object code.

Weaver – instruments code Weaver – instruments code (source or object) with advice.(source or object) with advice.

Adlux Consultancy Services Pvt Ltd

Page 11: Spring AOP

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

Page 12: Spring AOP

Advice

Adlux Consultancy Services Pvt Ltd

Page 13: Spring AOP

Advice

Adlux Consultancy Services Pvt Ltd

Page 14: Spring AOP

AdviceBefore 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

Page 15: Spring AOP

AdviceFrom 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

Page 16: Spring AOP

AdviceAfter 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

Page 17: Spring AOP

AdviceFrom 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

Page 18: Spring AOP

Advicepublic 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

Page 19: Spring AOP

AdviceAround 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

Page 20: Spring AOP

Advicepublic 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

Page 21: Spring AOP

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

Page 22: Spring AOP

Adlux Consultancy Services Pvt Ltd

Page 23: Spring AOP

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 advisorPointcutAdvisor=Pointcut + Advice

Adlux Consultancy Services Pvt Ltd

Page 24: Spring AOP

Adlux Consultancy Services Pvt Ltd

Page 25: Spring AOP

Pointcutspublic 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

Page 26: Spring AOP

PointcutsSpring defines two types of Point Cuts namely the Static and Dynamic Point Cuts. Static Pointcuts NameMatchMethod Pointcut Regular Expression PointcutNameMatchMethod 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

Page 27: Spring AOP

PointcutsMyInterface.javapublic 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

Page 28: Spring AOP

PointcutsApplicationContext.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

Page 29: Spring AOP

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>

Page 30: Spring AOP

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

Page 31: Spring AOP

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

Page 32: Spring AOP

PointcutsMyInterface.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

Page 33: Spring AOP

PointcutsApplicationContext.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

Page 34: Spring AOP

Adlux Consultancy Services Pvt Ltd

<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>

Pointcuts

Page 35: Spring AOP

Pointcuts

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

Adlux Consultancy Services Pvt Ltd

Page 36: Spring AOP

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

Page 37: Spring AOP

PointcutsDynamic 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

Page 38: Spring AOP

Adlux Consultancy Services Pvt Ltd

<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>

Pointcuts

Page 39: Spring AOP

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

Page 40: Spring AOP

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

Page 41: Spring AOP

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. target2. proxyInterfaces3. interceptorNames

Adlux Consultancy Services Pvt Ltd

Page 42: Spring AOP

AOP Proxy

Adlux Consultancy Services Pvt Ltd

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“/>

Page 43: Spring AOP

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

Page 44: Spring AOP

AOP Proxy1. 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

Page 45: Spring AOP

AOP Proxy2. 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

Page 46: Spring AOP

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

Page 47: Spring AOP

Adlux Consultancy Services Pvt Ltd