Notes: Spring AOP: 2: Advice

Ref: Spring documentation
Advice is associated with a pointcut expression, and runs before, after, or around method executions matched by the pointcut. The pointcut expression may be either a simple reference to a named pointcut, or a pointcut expression declared in place.

Before Advice
○ Before advice is declared in an aspect using the @Before annotation:

		import org.aspectj.lang.annotation.Aspect;
		import org.aspectj.lang.annotation.Before;
		public class BeforeExample {
			public void doAccessCheck() {
				// ...
			public void doAccessCheckWithInplacePointcut() {
			// ...

After-returning Advice

	○ @AfterReturning( pointcut="",
	public void doAccessCheck(Object retVal) {
			// ...

○ The name used in the returning attribute must correspond to the name of a parameter in the advice method.
○ When a method execution returns, the return value will be passed to the advice method as the corresponding argument value.
○ A returning clause also restricts matching to only those method executions that return a value of the specified type (Object in this case, which will match any return value).
○ Please note that it is not possible to return a totally different reference when using after-returning advice.

After throwing advice

	○  @AfterThrowing( pointcut="",
	public void doRecoveryActions(DataAccessException ex) {
		// ...

○ The name used in the throwing attribute must correspond to the name of a parameter in the advice method.
○ When a method execution exits by throwing an exception, the exception will be passed to the advice method as the corresponding argument value.
○ A throwing clause also restricts matching to only those method executions that throw an exception of the specified type (DataAccessException in this case).

After (finally) advice

	public void doReleaseLock() {
		// ...

Around advice

	public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
		// start stopwatch
		Object retVal = pjp.proceed();
		// stop stopwatch
		return retVal;

○ Around advice is declared using the @Around annotation.
○ The first parameter of the advice method must be of type ProceedingJoinPoint.
○ Within the body of the advice, calling proceed() on the ProceedingJoinPoint causes the underlying method to execute.
○ 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.
○ The value returned by the around advice will be the return value seen by the caller of the method. A simple caching aspect for example could return a value from a cache if it has one, and invoke proceed() if it does not.
○ Note that proceed may be invoked once, many times, or not at all within the body of the around advice, all of these are quite legal.

Advice parameters

Access to the current JoinPoint
○ Any advice method may declare as its first parameter, a parameter of type org.aspectj.lang.JoinPoint
○ For around advice ProceedingJoinPoint is mandatory as the first argument.
○ JoinPoint interface provides some methods like
§ getArgs()
§ getThis() returns the proxy object
§ getTarget()
§ getSignature()
§ toString() – prints a useful description of the method being advised

Passing parameters to advice

@Before(" && args(account,..)")
public void validateAccount(Account account) {
	// ...

Another way

@Pointcut(" && args(account,..)")
private void accountDataAccessOperation(Account account) {}

public void validateAccount(Account account) {
	// ...

Define the @Auditable annotation:

public @interface Auditable {
	AuditCode value();

Advice that matches the execution of @Auditable methods:
@Before(" && @annotation(auditable)")
public void audit(Auditable auditable) {
	AuditCode code = auditable.value();
	// ...

Determining argument names
○ Parameter names in pointcut expressions should match those used in advice and pointcut method signatures.

Parameter names are not available through Java reflection.
So Spring AOP uses the following strategies to determine parameter names:


Notes: Spring AOP: 2: Pointcuts

Ref: Spring documentation
Declaring A Pointcut
○ Pointcuts are collection of join-points.
○ Spring AOP only supports method execution join points for Spring beans. So pointcuts match only the execution of methods on Spring beans.
○ A pointcut declaration has two parts:
§ a signature comprising a name and any parameters,
§ a pointcut expression that determines exactly which method executions we are interested in.
○ In the @AspectJ annotation-style of AOP,
§ the pointcut signature is provided by a regular method definition,
§ the pointcut expression is indicated using the @Pointcut annotation
§ the method serving as the pointcut signature must have a void return type.
§ defining a pointcut named ‘anyOldTransfer’ that will match the execution of any method named ‘transfer’:

@Pointcut("execution(* transfer(..))")                 // the pointcut expression
			private void anyOldTransfer() {}            // the pointcut signature

Supported Pointcut Designators (PCDs) in Spring
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– 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 where the bean reference (Spring AOP proxy) is an instance of the given type
target – limits matching to join points where the target object (application object being proxied) is an instance of the given type
args – limits matching to join points where the arguments are instances of the given types
@target – limits matching to join points where the class of the executing object has an annotation of the given type
@args – limits matching to join points 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

Since Spring AOP supports joinpoints only as the execution of methods, all the above designators act as further filtering criteria in addition to the execution of methods.

Additionally Spring supports its own PCD called ‘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)
○ Since wildcard (*) is supported, if we have some naming conventions for your Spring beans we can quite easily write a ‘bean’ PCD expression to pick them out.
○ This PCD is instance based (not type based)

All above PCDs can be &&’ed, ||’ed, and ! (negated) too.

Combining Pointcuts

@Pointcut("execution(public * *(..))")                                                //Matched against any public method
private void anyPublicOperation() {}

@Pointcut("within(*)")    //execution of any public method in trading package
private void inTrading() {}

@Pointcut("anyPublicOperation() && inTrading()")                         //Above two combined
private void tradingOperation() {}

○ It is a best practice to build more complex pointcut expressions out of smaller named components as shown above.
○ When referring to pointcuts by name, normal Java visibility rules apply (you can see private pointcuts in the same type, protected pointcuts in the hierarchy, public pointcuts anywhere and so on). Visibility does not affect pointcut matching.

Any given pointcut is matched against public methods only.

For protected/private methods or constructors, consider the use of Spring-driven native AspectJ weaving (load time weaving) instead of Spring’s proxy-based AOP framework.

A well written pointcut should try and include at least the two types –kinded (execution, get, set, call, handler, etc )and scoping (within, withincode, etc) – whilst the contextual designators (ex- target, @annotation) may be included if wishing to match based on join point context, or bind that context for use in the advice.

Supplying either just a kinded designator or just a contextual designator will work but could affect weaving performance (time and memory used) due to all the extra processing and analysis.

Scoping designators are very fast to match and their usage means AspectJ can very quickly dismiss groups of join points that should not be further processed – that is why a good pointcut should always include one if possible.

Pointcut examples
“SystemArchitecture” aspect
○ Recommended approach – Define an aspect that captures common pointcut expressions for this purpose.

	import org.aspectj.lang.annotation.Aspect;
	import org.aspectj.lang.annotation.Pointcut;
	public class SystemArchitecture {
		* A join point is in the web layer if the method is defined 
		*in a type in the package or 
		*any sub-package  under that. */
		public void inWebLayer() {}
		public void inServiceLayer() {}
		public void inDataAccessLayer() {}
		public void businessService() {}

Notice that all the above pointcut methods are public and
so can be used anywhere.

A business service is the execution of any method defined on a service interface. This definition assumes that interfaces are placed in the “service” package, and that implementation types are in sub-packages.

If we group service interfaces by functional area (for example, in packages * and then the pointcut expression “execution(**.*(..))” could be used instead.

Alternatively, you can write the expression using the ‘bean’ * PCD, like so “bean(*Service)”. (Useful when we name Spring service beans in a consistent fashion.)

The most often used PCD is execution. The format of expression is
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)

The elements ret-type-pattern, name-pattern, param-pattern are mandatory.
○ We can use * on ret-type pattern and name-pattern
○ For param-pattern
§ () matches methods which take no arguments.
§ (..) indicates any number of parameters
§ (*) one or more arguments
§ (*, String) two arguments – first of any type, second of String type.

Some examples
○ any join point where the target object implements the AccountService interface:
§ target(
○ any join point which takes a single parameter, and where the argument passed at runtime is Serializable
§ args(
§ Note that the pointcut given above is different to execution(* *( the args version matches if the argument passed at runtime is Serializable, the execution version matches if the method signature declares a single parameter of type Serializable.


Notes: Spring: AOP: 1

Ref: Spring documentation
Spring framework supports AspectJ annotations
○ No dependency on AspectJ compiler or weaver. However, their use enables us to use full support of AspectJ. What do I mean by full support?

Enabling AspectJ support
○ The @AspectJ support is enabled by including the following element inside your spring configuration:
§ Which schema is needed for this?
○ Also include two AspectJ jars:
§ aspectjrt.jar
§ aspectjweaver.jar

Declaring and Aspect
○ Declare the bean in XML
○ Annotate the class with @Aspect

○ Aspects (classes annotated with @Aspect) may have methods and fields just like any other class. They may also contain pointcut, advice, and introduction (inter-type) declarations.
○ @Aspects are excluded from auto-proxying. So in Spring we cannot advise aspect themselves with other aspects.


Quick Notes: WSDL

WSDL is a document written in XML. The document describes a Web service. It specifies the location of the service and the operations (or methods) the service exposes.

WSDL main elements:

Element Defines
The data types used by the web service
The messages used by the web service
The operations performed by the web service
The communication protocols used by the web service

WSDL Example

<message name="getTermRequest">
  <part name="term" type="xs:string"/>

<message name="getTermResponse">
  <part name="value" type="xs:string"/>

<portType name="glossaryTerms">
  <operation name="getTerm">
    <input message="getTermRequest"/>
    <output message="getTermResponse"/>

WSDL Binding With SOAP

<message name="getTermRequest">
  <part name="term" type="xs:string"/>

<message name="getTermResponse">
  <part name="value" type="xs:string"/>

<portType name="glossaryTerms">
  <operation name="getTerm">
    <input message="getTermRequest"/>
    <output message="getTermResponse"/>

<binding type="glossaryTerms" name="b1">
   <soap:binding style="document or rpc"
   transport="" />
     <soap:operation soapAction=""/>
	     <input><soap:body use="literal"/></input>
	     <output><soap:body use="literal"/></output>

Quick Notes: SOAP

SOAP is a simple XML-based protocol to let applications exchange information over HTTP.
# SOAP is a protocol for accessing a Web Service.
# SOAP stands for Simple Object Access Protocol
# SOAP is a communication protocol
# SOAP is for communication between applications
# SOAP is a format for sending messages

A SOAP message is an ordinary XML document containing the following elements:
* An Envelope element -identifies the XML document as a SOAP message
* A Header element that contains header information
* A Body element that contains call and response information
* A Fault element containing errors and status information

A SOAP HHTP Web Service Request:

POST /item HTTP/1.1
Content-Type: application/soap+xml; charset=utf-8
Content-Length: 250

<?xml version="1.0"?>

	  <m:GetPrice xmlns:m="">

A SOAP Response

	  <m:GetPriceResponse xmlns:m="http://URL/prices">

SOAP Fault Element
If a Fault element is present, it must appear as a child element of the Body element.
A Fault element can only appear once in a SOAP message.

Sub Element Description
A code for identifying the fault
A human readable explanation of the fault
Information about who caused the fault to happen
Holds application specific error information related to the Body element

Error Description
VersionMismatch Found an invalid namespace for the SOAP Envelope element
MustUnderstand An immediate child element of the Header element, with the
mustUnderstand attribute set to “1”, was not understood
Client The message was incorrectly formed or contained incorrect information
Server There was a problem with the server so the message could not proceed