Spring Study Notes - Copyright © 2010 Gavin Lasnitzki Index   Notes   Objectives
AOP

6. Aspect Oriented Programming with Spring

Objectives: 2. AOP

6.1. Introduction Key

Objectives: 2.1 What Problem Does AOP Solve?

Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure.
Key unit of modularity in OOP is the class. Key unit of modularity in AOP is the aspect.
Aspects enable the modularization of concerns that cut across multiple types and objects (crosscutting concerns).

AOP is used in the Spring Framework to provide declarative enterprise services, especially as a replacement for EJB declarative services (such as transaction management) and allow users to implement custom aspects, complementing their use of OOP with AOP.

6.1.1. AOP concepts Key Question

Objectives: 2.2 Core AOP Concepts

Terms Question

  • Aspect: a modularization of a concern that cuts across multiple classes.
  • Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.
  • Advice: action taken by an aspect at a particular join point.
  • Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut.
  • Introduction: declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and its implementation)
  • Target object: object being advised by one or more aspects.
  • AOP proxy: an object created by the AOP framework in order to implement the aspect contracts.
  • Weaving: linking aspects with other application types or objects to create an advised object.

Types of advice Question

  • 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. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

6.1.2. Spring AOP capabilities and goals

Spring AOP is implemented in pure Java. There is no need for a special compilation process. Spring AOP does not need to control the class loader hierarchy, and is thus suitable for use in a J2EE web container or application server

Spring AOP currently supports only method execution join points (advising the execution of methods on Spring beans). Field interception is not implemented.

Spring AOP provides a close integration between AOP implementation and Spring IoC to help solve common problems in enterprise applications.

Spring AOP is a proxy-based frameworks.

6.1.3. AOP Proxies

Spring AOP defaults to using standard J2SE dynamic proxies for AOP proxies.
Spring AOP can also use CGLIB proxies to proxy classes.

6.2. @AspectJ support

Objectives: 2.3 Defining Pointcuts, implementing advice

@AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.
Spring 2.0 interprets the same annotations as AspectJ 5, using a library supplied by AspectJ for pointcut parsing and matching.
The AOP runtime is still pure Spring AOP though, and there is no dependency on the AspectJ compiler or weaver.

6.2.1. Enabling @AspectJ Support Question

By autoproxying we mean that if Spring determines that a bean is advised by one or more aspects, it will automatically generate a proxy for that bean to intercept method invocations and ensure that advice is executed as needed.

The @AspectJ support is enabled by including the following element inside your spring configuration:
Add the following jars to your classpath of your application: aspectjweaver.jar, aspectjrt.jar

Key XML Scheme-based

 

DTD based

6.2.2. Declaring an aspect Key

Any bean defined in your application context with a class that is an @AspectJ aspect will be automatically detected.

6.2.3. Declaring a pointcut Key

Defines a pointcut expression names "anyOldTransfer" that will be triggered for the "transfer" method:

6.2.3.1. Supported Pointcut Designators Question

Key Spring AOP supports the following AspectJ pointcut designators (PCD)

  • execution - for matching method execution join points, this is the primary pointcut designator you will use when working with Spring AOP
  • within - limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP)
  • this - limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type
  • target - limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type
  • args - limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types
  • @target - limits matching to join points (the execution of methods when using Spring AOP) where the class of the executing object has an annotation of the given type
  • @args - limits matching to join points (the execution of methods when using Spring AOP) where the runtime type of the actual arguments passed have annotations of the given type(s)
  • @within - limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP)
  • @annotation - limits matching to join points where the subject of the join point (method being executed in Spring AOP) has the given annotation

Spring AOP also supports an additional PCD named 'bean'.
This PCD allows you to limit the matching of join points to a particular named Spring bean, or to a set of named Spring beans (when using wildcards). The "idOrNameOfBean" token can be the name of any Spring bean: limited wildcard support using the "*" character is provided

Due to the proxy-based nature of Spring's AOP framework, protected methods are by definition not intercepted.

Key PCD supports boolean operators: and (&&), or (||), not (!)

6.2.3.2. Combining pointcut expressions Key

You can refer to pointcut expressions by name.
This allows you to build more complex pointcut expressions out of smaller named components.

6.2.3.3. Sharing common pointcut definitions

6.2.3.4. Examples Question

See examples in Spring Reference Documentation.

 

Summary

All parts except the returning type pattern (ret-type-pattern in the snippet above), name pattern, and parameters pattern are optional.

The returning type pattern determines what the return type of the method must be in order for a join point to be matched.
Most frequently you will use * as the returning type pattern, which matches any return type.
A fully-qualified type name will match only when the method returns the given type.

The name pattern matches the method name.
You can use the * wildcard as all or part of a name pattern

The parameters pattern is slightly more complex: () matches a method that takes no parameters, whereas (..) matches any number of parameters (zero or more).
The pattern (*) matches a method taking one parameter of any type.

See AspectJ Programming Guide for more information.
See 6.2.3.4. for some pointcut examples.

6.2.4. Declaring advice Key Question

6.2.4.1. Before advice

Before advice is declared in an aspect using the @Before annotation.

6.2.4.2. After returning advice

After returning advice runs when a matched method execution returns normally. It is declared using the @AfterReturning annotation. Question

To access the actual return value in the advice, use:

The name used in the returning attribute must correspond to the name of a parameter in the advice method.
It is not possible to return a totally different reference when using after-returning advice

6.2.4.3. After throwing advice

After throwing advice runs when a matched method execution exits by throwing an exception. It is declared using the @AfterThrowing annotation.

To access the exception in the advice, use:

A throwing clause also restricts matching to only those method executions that throw an exception of the specified type.

6.2.4.4. After (finally) advice

After (finally) advice runs however a matched method execution exits.
It is declared using the @After annotation.
It must to handle both normal and exception return conditions.

6.2.4.5. Around advice

It can work both before and after the method execute.
Determine if the method actually gets to execute at all.

Call proceed() on the ProceedingJoinPoint in the body of the advice to execute the underlying method.
The proceed method may also be called passing in an Object[] - the values in the array will be used as the arguments to the method execution when it proceeds.

6.2.4.6. Advice parameters Key

Spring AOP fully typed advice - meaning that you declare the parameters you need in the advice signature.

Any advice method may declare as its first parameter, a parameter of type org.aspectj.lang.JoinPoint.
Around advice is required to declare a first parameter of type ProceedingJoinPoint.

Passing parameters to advice
To make argument values available to the advice body, you can use the binding form of args.

 

Determining argument names

  1. If the parameter names have been specified by the user explicitly, then the specified parameter names are used.
    Use the "argNames" attribute of either the advice or pointcut annotation.
    If the first parameter is of the JoinPoint you may leave out the name of the parameter from the value of the "argNames" attribute.
  2. Spring AOP will look at the debug information for the class and try to determine the parameter names from
    the local variable table.
  3. Spring AOP will attempt to deduce the pairing of binding variables.
  4. If all of the above strategies fail then an IllegalArgumentException will be thrown.

Proceeding with arguments
To call a proceed call with arguments (consistently across Spring AOP and ASPECTJ), ensure that the advice signature binds each of the method parameters in order.

6.2.4.7. Advice ordering Key

The highest precedence advice runs first "on the way in" and last "on the way out".
Aspect can implement org.springframework.core.Ordered interface or use the Order annotation.

6.2.5. Introductions

Introductions (known as inter-type declarations in AspectJ) enable an aspect to declare that advised objects implement a given interface, and to provide an implementation of that interface on behalf of those objects.

6.2.6. Aspect instantiation models

Excluded from Exam

6.2.7. Example

6.3. Schema-based AOP support Key

Objectives: 2.3 Defining Pointcuts, implementing advice

Importing AOP schema

6.3.1. Declaring an aspect Key

6.3.2. Declaring a pointcut Key

 

With Java 5, you can refer to named pointcuts defined in types (@Aspects) within the pointcut expression.
It easier to use "and", "or", "not" than "&&", "||" and "!" in an xml attribute.
Pointcuts defined in the XML configuration cannot be used as to form composite pointcuts.

6.3.3. Declaring advice Key

6.3.3.1. Before advice


To define the pointcut inline instead, replace the "pointcut-ref" attribute with a "pointcut" attribute.
The method attribute identifies a method that provides the body of the advice.

6.3.3.2. After returning advice

6.3.3.3. After throwing advice

6.3.3.4. After (finally) advice

6.3.3.5. Around advice

6.3.3.6. Advice parameters

The "arg-names" attribute of the advice element allows you to specify the argument names.

6.3.3.7. Advice ordering

6.3.4. Introductions

6.3.5. Aspect instantiation models

Excluded from Exam

6.3.6. Advisors Question

An advisor is like a small self-contained aspect that has a single piece of advice.
Use the <aop:advisor> element.
Commonly used with transactional advice.

6.3.7. Example

6.4. Choosing which AOP declaration style to use Key

Use the simplest thing that can work.

6.4.1. Spring AOP or full AspectJ? Key

Spring AOP

  • (Pro) Spring AOP is simpler than using full AspectJ as there is no requirement to introduce the AspectJ compiler / weaver into your development and build processes.
  • (Pro) Simple to advise the execution of operations on Spring beans.

AspectJ

  • (Pro) Use if you need to advise objects not managed by the Spring container
  • (Pro) Use if you need to advise join points other than simple method executions (for example, field get or set join points).

6.4.2. @AspectJ or XML for Spring AOP? Key

If you are using Spring AOP, you need to choose your configuration style.

@AspectJ

  • (Pro) Can be used by both Spring AOP and AspectJ (if you switch at a later stage)
  • (Pro) There is a single module - the aspect (DRY)
  • (Pro) Supports the combining of named pointcuts (to create compound expressions)

XML

  • (Pro) You need to use XML if you are not running of Java 5+
  • (Pro) Familiar to existing Spring users.
  • (Pro) Easy to change without re-compiling.
  • (Pro) Clearer from your configuration what aspects are present in the system.
  • (Con) It does not fully encapsulate the implementation of the requirement it addresses in a single place (not DRY).
  • (Con) Only the "singleton" aspect instantiation model is supported.
  • (Con) Not possible to combine named pointcuts.

 

6.5. Mixing aspect types

@AspectJ style and XML configuration style can co-exist without difficulty.

6.6. Proxying mechanisms

Spring AOP uses either JDK dynamic proxies or CGLIB to create the proxy.
JDK is the default. All interfaces will be automatically proxied.
To specify the proxying mechanism, us the "proxy-target-class" attribute.
Use CGLIB if you need to advise a method that is not in an interface.
When using CGLIB, final methods can not be advised, the jar files will need to be in your classpath and the constructor of your proxied object will be called twice.

@AspectJ with CGLIB

XML scheme with CGLIB

Using 'proxy-target-class="true"' on <tx:annotation-driven/>, <aop:aspectj-autoproxy/> or <aop:config/> elements will force the use of CGLIB proxies for all them.

6.6.1. Understanding AOP proxies

Spring AOP is proxy-based, which means that self-invocation is not going to result in the advice associated with a method invocation getting a chance to execute.

6.7. Programmatic creation of @AspectJ Proxies

It is also possible programmatically to create proxies that advise target objects.

6.8. Using AspectJ with Spring applications

Excluded from Exam

6.8.1. Using AspectJ to dependency inject domain objects with Spring

6.8.1.1. Unit testing @Configurable objects

6.8.1.2. Working with multiple application contexts

6.8.2. Other Spring aspects for AspectJ

6.8.3. Configuring AspectJ aspects using Spring IoC

6.8.4. Load-time weaving with AspectJ in the Spring Framework

6.8.4.1. A first example

6.8.4.2. Aspects

6.8.4.3. 'META-INF/aop.xml'

6.8.4.4. Required libraries (JARS)

6.8.4.5. Spring configuration

6.8.4.6. Environment-specific configuration

6.9. Further Resources

7. Spring AOP APIs

Excluded from Exam

7.1. Introduction

7.2. Pointcut API in Spring

7.2.1. Concepts

7.2.2. Operations on pointcuts

7.2.3. AspectJ expression pointcuts

7.2.4. Convenience pointcut implementations

7.2.4.1. Static pointcuts

7.2.4.2. Dynamic pointcuts

7.2.5. Pointcut superclasses

7.2.6. Custom pointcuts

7.3. Advice API in Spring

7.3.1. Advice lifecycles

7.3.2. Advice types in Spring

7.3.2.1. Interception around advice

7.3.2.2. Before advice

7.3.2.3. Throws advice

7.3.2.4. After Returning advice

7.3.2.5. Introduction advice

7.4. Advisor API in Spring

7.5. Using the ProxyFactoryBean to create AOP proxies

7.5.1. Basics

7.5.2. JavaBean properties

7.5.3. JDK- and CGLIB-based proxies

7.5.4. Proxying interfaces

7.5.5. Proxying classes

7.5.6. Using 'global' advisors

7.6. Concise proxy definitions

7.7. Creating AOP proxies programmatically with the ProxyFactory

7.8. Manipulating advised objects

7.9. Using the "autoproxy" facility

7.9.1. Autoproxy bean definitions

7.9.1.1. BeanNameAutoProxyCreator

7.9.1.2. DefaultAdvisorAutoProxyCreator

7.9.1.3. AbstractAdvisorAutoProxyCreator

7.9.2. Using metadata-driven auto-proxying

7.10. Using TargetSources

7.10.1. Hot swappable target sources

7.10.2. Pooling target sources

7.10.3. Prototype target sources

7.10.4. ThreadLocal target sources

7.11. Defining new Advice types

7.12. Further resources