Spring aop concepts

50 %
50 %
Information about Spring aop concepts

Published on February 22, 2014

Author: RushiBShah



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.

By: Rushi B Shah

 What is AOP?  Why it is required?  AOP Terminology  AspectJ as an AOP framework  AspectJ Annotation Syntax  Different types of Advices and its Implementation

 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 crosscutting concerns  AOP introduces loose coupling between core and crosscutting concerns  AOP is nothing but modularization of concerns

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

          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.

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

      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} {methodname} {parameters} {throws exception} )

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

Type Kinded Dynamic Scope Syntax Meaning the method name execution(* set*(*)) matches a method-execution join point, if starts with "set" and there is exactly one argument of any type and any one return type this(Point) within(*) pointcut set() : execution(* Composed set*(*) ) && this(Point) && within(*); 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. matches any join point in any type in the package. The * is one form of the wildcards that can be used to match many things with one signature. 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 package.

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

import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class BeforeExample { @Before("execution(**.*(..))") public void doAccessCheck() { // method definition } }

<aop:aspectj-autoproxy /> <bean id="customerBo“ class=""/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <!-- @Before --> <aop:pointcut id="pointCutBefore“ expression="execution(*" /> <aop:before method="logBefore" pointcutref="pointCutBefore" /> </aop:config>

    import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.AfterReturning; @Aspect public class AfterReturningExample {  @AfterReturning(pointcut=" .dataAccessOperation()”, returning=“retVal”)  public void doAccessCheck() {  // method definition  }  }

<aop:aspectj-autoproxy /> <bean id="customerBo“ class=""/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <!-- @AfterReturning --> <aop:pointcut id="pointCutAfterReturning“ expression="execution(* e(..))" /> <aop:after-returning method="logAfterReturning" returning="result" pointcut-ref="pointCutAfterReturning" /> </aop:config>

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

<aop:aspectj-autoproxy /> <bean id="customerBo“ class=""/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <!-- @AfterThrowing --> <aop:pointcut id="pointCutAfterThrowing“ expression="execution(* on(..))" /> <aop:after-throwing method="logAfterThrowing" throwing="error" pointcut-ref="pointCutAfterThrowing" /> </aop:config>

import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.After; @Aspect public class AfterFinallyExample { @After(" ataAccessOperation()") public void doReleaseLock() { // method definition } }

<aop:aspectj-autoproxy /> <bean id="customerBo“ class=""/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <!-- @After --> <aop:pointcut id="pointCutAfter“ expression="execution(*" /> <aop:after method="logAfter" pointcut-ref="pointCutAfter" /> </aop:aspect> </aop:config>

import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.ProceedingJoinPoint; @Aspect public class AroundExample { @Around(" nessService()") 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; } }

<aop:aspectj-autoproxy /> <bean id="customerBo“ class=""/> <!--@Aspect --> <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> <aop:config> <aop:aspect id="aspectLoggging" ref="logAspect" > <aop:pointcut id="pointCutAround“ expression="execution(* (..))" /> <aop:around method="logAround" pointcutref="pointCutAround" /> </aop:aspect> </aop:config>

@Aspect public class LoggingAspect { @Before("execution(* stomerBo.addCustomer(..))") public void logBefore(JoinPoint joinPoint) { //method definition } } @Aspect public class OtherAspect { @Before(LoggingAspect.logBefore()) //AspectClassName. methodname public void otherMethod(JoinPoint joinpoint) { //method definition} }

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

       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.

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

Thank You

Add a comment

Related presentations

Presentación que realice en el Evento Nacional de Gobierno Abierto, realizado los ...

In this presentation we will describe our experience developing with a highly dyna...

Presentation to the LITA Forum 7th November 2014 Albuquerque, NM

Un recorrido por los cambios que nos generará el wearabletech en el futuro

Um paralelo entre as novidades & mercado em Wearable Computing e Tecnologias Assis...

Microsoft finally joins the smartwatch and fitness tracker game by introducing the...

Related pages

Chapter 6. Aspect Oriented Programming with Spring

Aspect Oriented Programming with Spring. 6.1. Introduction. ... Let us begin by defining some central AOP concepts. These terms are not Spring-specific.
Read more

Chapter 5. Spring AOP: Aspect Oriented Programming with Spring

Spring AOP: Aspect Oriented Programming with Spring; Prev ... Let us begin by defining some central AOP concepts. These terms are not Spring-specific.
Read more

Spring AOP - Concepts and XML Configuration - StudyTrails

Spring Aspect Oriented Programming Using XML ... Create the Person (see sample code below). Create members name and email (see lines 5-6 below)
Read more

Spring AOP Tutorial | Aspect Oriented Programming - javatpoint

Spring AOP Tutorial or Aspect Oriented Programming with examples, spring aop tutorial, spring dependency injection, ... AOP Concepts and Terminology.
Read more

Spring In Context: Core Concepts - Spring by Example

Spring In Context: Core Concepts. Susan Kerschbaumer. David Winterfeldt. 2009 ...The architecture that actually predominates in practice has yet to be ...
Read more

Chapter 9. Aspect Oriented Programming with Spring.NET

Aspect-Oriented Programming (AOP) ... Spring.NET offers the concept of a TargetSource, expressed in the Spring.Aop.ITargetSource interface.
Read more

Spring - AOP with Spring Framework - Tutorialspoint

AOP with Spring Framework ... Spring AOP module provides interceptors to intercept an ... let us become familiar with the AOP concepts and terminology.
Read more

Chapter 13. Aspect Oriented Programming with Spring.NET

Chapter 13. Aspect Oriented Programming with Spring.NET. 13.1. Introduction. Aspect-Oriented Programming ... The pointcut concept is the key to AOP, ...
Read more

Spring Chapter 12 - Spring AOP Concepts - YouTube

Spring Chapter 12 - Spring AOP Concepts ... Spring AOP tutorial - Part 1 | Aspect Oriented Programming Tutorial Part -1 - Duration: 14:43.
Read more

An Introduction to Spring AOP - DZone Java

An Introduction to Spring AOP This article discusses ... (called cross-cutting concerns) to objects. AOP need not seem like a foreign concept, ...
Read more