spring aop concepts

25
Spring AOP Concepts By: Rushi B Shah

Upload: rushibshah

Post on 26-May-2015

425 views

Category:

Technology


2 download

DESCRIPTION

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.

TRANSCRIPT

Page 1: Spring aop concepts

Spring AOP Concepts

By: Rushi B Shah

Page 2: Spring aop concepts

What is AOP?

Why it is required?

AOP Terminology

AspectJ as an AOP framework

AspectJ Annotation Syntax

Different types of Advices and its Implementation

Agenda

Page 3: Spring aop concepts

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 cross-cutting concerns

AOP introduces loose coupling between core and cross-cutting concerns

AOP is nothing but modularization of concerns

What is AOP?

Page 4: Spring aop concepts

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.

Why is AOP required?

Page 5: Spring aop concepts

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.

AOP Terminology

Page 6: Spring aop concepts

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

Different types of Advices

Page 7: Spring aop concepts

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} {method-name} {parameters} {throws exception} )

Pointcut Expression Syntax

Page 8: Spring aop concepts

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.

How does Spring process AspectJ Annotations?

Page 9: Spring aop concepts

Type Syntax Meaning

Kinded execution(* set*(*))

matches a method-execution join point, if the method name starts with "set" and there is exactly one argument of any type and any one return type

Dynamic this(Point)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.

Scope within(com.company.*)

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.

Composedpointcut set() : execution(* set*(*) ) && this(Point) && within(com.company.*);

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.

AspectJ Pointcut Designator

Page 10: Spring aop concepts

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

Using AOP in Spring framework

Page 11: Spring aop concepts

import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;@Aspectpublic class BeforeExample { @Before("execution(*com.xyz.myapp.dao.*.*(..))") public void doAccessCheck() {

// method definition } }

Declaring Before Advice using AspectJ Annotation Syntax

Page 12: Spring aop concepts

<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" pointcut-ref="pointCutBefore" /></aop:config>

Declaring Before Advice using AspectJ XML Configuration

Page 13: Spring aop concepts

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

}

}

Declaring After Returning Advice using AspectJ Annotation Syntax

Page 14: Spring aop concepts

<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.addCustomerReturnValue(..))" /><aop:after-returning method="logAfterReturning" returning="result" pointcut-ref="pointCutAfterReturning" /></aop:config>

Declaring After Returning Advice using AspectJ XML Configuration Syntax

Page 15: Spring aop concepts

import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.AfterThrowing;@Aspect public class AfterThrowingExample { @AfterThrowing(pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()", throwing="ex") public void doRecoveryActions(DataAccessException ex) { // method definition } }

Declaring After Throwing Advice using AspectJ Annotation Syntax

Page 16: Spring aop concepts

<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.addCustomerThrowException(..))" />

<aop:after-throwing method="logAfterThrowing" throwing="error" pointcut-ref="pointCutAfterThrowing" /></aop:config>

Declaring After Throwing Advice using AspectJ XML Configuration Syntax

Page 17: Spring aop concepts

import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.After;@Aspect public class AfterFinallyExample { @After("com.xyz.myapp.SystemArchitecture.dataAccessOperation()") public void doReleaseLock() { // method definition

}}

Declaring After(finally) Advice using AspectJ Annotation Syntax

Page 18: Spring aop concepts

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

Declaring After(finally) Advice using AspectJ XML Configuration Syntax

Page 19: Spring aop concepts

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.businessService()") 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;

} }

Declaring Around Advice using AspectJ Annotation Syntax

Page 20: Spring aop concepts

<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" pointcut-ref="pointCutAround" /> </aop:aspect></aop:config>

Declaring Around Advice using AspectJ XML Configuration Syntax

Page 21: Spring aop concepts

@Aspectpublic class LoggingAspect {@Before("execution(*com.mkyong.customer.bo.CustomerBo.addCustomer(..))")

public void logBefore(JoinPoint joinPoint) { //method definition }

  }@Aspectpublic class OtherAspect {@Before(LoggingAspect.logBefore()) //AspectClassName. methodname

public void otherMethod(JoinPoint joinpoint) { //method definition}

}

How to Reuse pre-declared Pointcut Expression

Page 22: Spring aop concepts

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

Advice Execution Order (If applied on same method)

Page 23: Spring aop concepts

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.

Choosing which AOP declaration style to use

Page 24: Spring aop concepts

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.

Proxy Mechanism in Spring AOP

Page 25: Spring aop concepts

Thank You