Showing posts with label spring-aop. Show all posts
Showing posts with label spring-aop. Show all posts

Wednesday, June 29, 2011

Writing method interceptors using Spring AOP

Spring is a great Java technology that has become a very popular application framework during the past few years. My intention is not to go through the whole concepts and architectural details of the framework, because that kind of information can be easily looked up starting at http://www.springframework.org. As the article title indicates, I intend to provide hands-on examples showing the minimal requirements to bundle certain Spring functionalities in your Java applications. So, because I will not go into the “what’s under the hood” approach unless absolutely necessary, most of the examples might require the knowledge of basic Spring concepts. Anyway, the basic idea is that you must RTFM before deciding if Spring is right for your application.
The first example is a short look at a simple method intercepting strategy. You can read all about this and the whole Spring AOP API here.The source code for this example can be found here. In the project directory run ant compile run to launch the application.
For the beginning let’s consider that we have the service MyService that that has a method doSomething() performing an operation which takes a long time to execute. Below you can see the (pretty dumb) code of this method.
public class MyService {
  public void doSomething() {
    for (int i = 1; i < 10000; i++) {
      System.out.println("i=" + i);
    }
  }
}

In order to print out the performance statistics on the method call, we must first implement the interceptor that actually calculates the execution time for this method. To do this we need to implement the org.aopalliance.intercept.MethodInterceptor interface shipped with Spring. This is actually a callback providing access to the actual call of the methods of our service. The JavaDoc for this interface is here.

public class ServiceMethodInterceptor implements MethodInterceptor {
  public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    long startTime = System.currentTimeMillis();
    Object result = methodInvocation.proceed();
    long duration = System.currentTimeMillis() - startTime;
    Method method = methodInvocation.getMethod();
    String methodName = method.getDeclaringClass().getName()  
                                   + "." + method.getName();
    System.out.println("Method '" + methodName  
                         + "' took " + duration + " milliseconds to run");
    return null;
  }
}

Next we need to proxy our service in order to obtain an instance whose methods are being intercepted by our ServiceMethodInterceptor. To achieve this, all it takes is a little magic in Spring’s bean configuration file, as you can see below.

<beans>
  <bean id="myService" class="com.test.MyService">
  </bean>

  <bean id="interceptor" class="com.test.ServiceMethodInterceptor">
  </bean>

  <bean id="interceptedService" class="org.springframework
                      .aop.framework.ProxyFactoryBean">
    <property name="target">
      <ref bean="myService"/>
    </property>
    <property name="interceptorNames">
      <list>
        <value>interceptor</value>
      </list>
    </property>
  </bean>
</beans>

The key in this XML snippet is Spring’s built-in class org.springframework.aop.framework.ProxyFactoryBean which provides the actual proxying of our service. In order to obtain the desired effect we must set the target and interceptorNames properties for this bean. The target property represents the name of the bean that we want to proxy, which in our case is the myService bean. The interceptorNames property holds a list of bean names that will be used as interceptors for the proxied bean. So, yes, you can define more than one interceptor for your bean.
As everything seems to be packed pretty nice, all we need to do now is to have our service instantiated using Spring and call itâs doSomething method.

public class Test {
  public static void main(String[] args) {
    ApplicationContext ctx =  
           new ClassPathXmlApplicationContext("com/test/applicationContext.xml");
    MyService myService = (MyService)ctx.getBean("interceptedService");
    myService.doSomething();
  }
}

So we need to look up the interceptedService bean in order to get the proxied service, but if we choose to remove the performance monitor we can simply lookup the initial myService bean.
Normally, after the method doSomething has run, you should see, as the last output line, something like this:
Method 'com.test.MyService.doSomething' took 281 milliseconds to run

Except from the MethodInterceptor Spring also offers other method interception strategies. For example you can choose to handle a method execution right before or immediately after the actual call, or when an exception is thrown during the execution of your method. The reference documentation about these types of interceptors that Spring offers is available here.

Please note that basic performance monitoring can also be achieved by using Spring’s built-in PerformanceMonitorInterceptor. We used this logic just as a sample for method intercepting, but as your intuition might tell you, this is just one of the many things you can do with this feature of Spring. For example, if you need to implement a fine-grained security module, you might choose not to allow the method call to execute if the user does not have rights on the business method. So, basically, you will have to see for yourself how you can use this functionality in your application.
I hope you find this article useful.

Tuesday, April 26, 2011

Spring AOP vs AspectJ

Spring AOP is simpler than using AspectJ as there is no requirement to introduce the compiler into build processes for Compile Time Weaving. 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 created by the Spring container, 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).When using AspectJ, you have the choice of the AspectJ language syntax or the @AspectJ annotation style. Clearly, if you are not using Java 5+ then the choice has been made for you… use the code style. If aspects play a large role in your design, and you are able to use the AspectJ Development Tools (AJDT) plugin for Eclipse, then the AspectJ language syntax is the preferred option: it is cleaner and simpler because the language was purposefully designed for writing aspects. If you are not using Eclipse, or have only a few aspects that do not play a major role in your application, then you may want to consider using the @AspectJ style and sticking with a regular Java compilation in your IDE, and adding an aspect weaving phase to your build script.

Moreover following are the conclusive differences in Spring AOP and AspectJ.
Spring-AOP : Runtime weaving through proxy using concept of dynamic proxy if interface exists or cglib library if direct implementation provided.
AspectJ: Compile time weaving through AspectJ Java Tools(ajc compiler) if source available or post compilation weaving (using compiled files).Also, load time weaving with Spring can be enabled – it needs the aspectj definition file and offers flexibility. Compile time weaving can offer benefits of performance (in some cases) and also the joinpoint definition in Spring -aop is restricted to method definition only which is not the case for AspectJ.

Weaving style of working with AOP

 Earlier we saw proxy style of handling aop, now we will see weaving style. Spring 2.5 supported LTW (load time weaving).
Weaving means bytecode instrumentation.

Types of Weaving
Code weaving comes in three flavors:

  • Load-time weaving(LTW): Aspect weaving is performed by the class loader when classes are first loaded.
    Weave class files when being loaded in VM
    i.e. Add aspect to class files OR Aspect + class files
  • Compile-time weaving: Aspects are weaved into the class files when they are compiled.
    Aspect + source code = class files
  • Binary Weaving (linker)
    Aspect + source/byte code = class files


Aspectwerkz and AspectJ works with both compile and load-time weaving.

Compile time weaving and binary weaving requires a seperate AspectJ compiler, which has nothing to do with spring. You will have to seperate lean AspectJ or try it out. Eclipse plugins are also available for AspectJ making it easier to achieve the same.

See how to configure the weaving method and proxy method of AOP in spring.


AOP support in spring

In spring, AOP is supported via 2 methods:
Click on the links to read in detail.

How to configure any of the methods in spring?

We need to decide with approach to use:
  • <aop:aspectj-autoproxy/> to enable proxy based AOP implementation.
  • <context:load-time-weaver /> to enable LTW ( load time weaving ) of classes.
    Works for Tomcat 5.5+, dm server 1.0+, weblogic 10, oc4j 10.x, glassfish.
    For standalone applications use:
    java-javaagent:spring-agent.jar ...

Spring's dynamic proxies for AOP

Till spring 2.0, spring's implementation is called as proxy-based AOP implementation irrespective of which AOP library you are using. These proxies essentially wrap a targ et object (eg. BankAccount instance) in order to apply aspects (SecurityManager calls) before and after delegation of the target object.
These proxies appear as the class of the target object to any client, making the proxies simple drop-in replacements anywhere the original target is used.

So before using AOP, code used to look like this:

But after using proxy pattern the code will look like this:


Since the client would be unaware that he is taling to the different class, the Proxy generated by Spring would either be sublcass of BankAccount or implement interfaces exposed by BankAccount class so that client class remains transparent to the changes in the configuration.
Client invokes methods exposed by the proxy, which in turn will execute interceptors configured for target bean.

Client will never know that he is calling the method of a proxy class. Proxy classes are wrappers around our actual components and contain same signature methods taking it 100% transparent to the system.

In spring, proxy classes are used in many places apart from AOP as well.

See how to configure the weaving method and proxy method of AOP in spring.

AOP : Tutorial

AOP introduction

Need For AOP
First see need for aop.

Defining AOP
Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure.

Aspects
Aspects are concern of the application that apply themselves across the entire system. The SecurityManager is one example of system-wide aspect, as its hasPermissions methods are used by many methods. Other typical aspects include logging, auditing, exception handling, performance monitoring, transaction management. See need for aop . These are also called advice, interceptor or concernts.

Who handles these concerns?
These types of concerns are best left to framework hosting the application, allowing developers to focus more on business logic.

AOP frameworks available
There are lots of frameworks available for AOP in java, and each one calls the concerns with differnt names, written within parenthesis:
  • AOPAlliance API (interceptor)
  • AspectJ (Aspect)
  • Spring AOP (Advice)
  • Spring-AspectJ combination (Aspect)
For AOPAlliance, click here.
AspectJ plugin for eclipse ide can be downloaded from here.
For spring we will see in tutorial continued. Since spring 2.0 AspectJ is the best AOP implementation, so its also combined in spring as told above.

Weaving or interjection
An AOP framework, such as spring AOP will interject or weave aspect code transparently into your domain model at runtime or compile time. This means that while we may have removed calls to the SecurityManager from the Business class, it will be still executed in AOP framework.
The beauty of this technique is that both the domain model (eg. our business code, say BankAccount) and its user or client such as Customer, both are unaware of the enhancement to the code.

What are cross-cutting concerns?

The Separation of Concerns principal states that a concern is any piece of interest or focus in a program. Think about it in terms of a layered architecture with the layers being UI, Business, Service and Data. Each one of these layers is its own concern. These layers are "horizontal".
The UI layer is only concerned with display and user interaction and not with database connectivity; as such, the data layer is not concerned with determining if a user is eligible for a car loan (business rules). When you design your code you usually break up these concerns into their own modules (classes, assemblies, etc).
Logging, security, error handling and caching are also concerns but where do they fit in to this layered architecture? The answer is everywhere. These concerns are "vertical" or "cross-cutting" or "orthogonal" which means they touch each layer. UI needs logging and error handling just as the other layers do too.

More terminology on AOP.


Need for AOP

Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. 

Consider a following method code (say in a webservice method):

try{
   //start new session
   //some business logic
   //commit transaction
}catch(Exception ex)
{
   //handle exception
}finally{
   //close session
}
//logging
//return the output


So like this method above, there will be lots of other methods similar to this....But don't you think it will be nice if  we only deal with business logic, rather than writing the repeatative code like handling exceptions, logging,security management, etc. These code tidbits are called concerns or aspects or advices (though described below). These are used interchangeably, though there are slight differences, which we will see in course of time.

So this is where AOP comes into picture. We can simply write our code as a simple business logic, without dealing with above mentioned concerns or repeatative code. For eg. for security checks, you can add the authorization into the execution path with a type of IOC implementation called AOP or aspect oriented programming. 

See Aop introduction

Sunday, March 20, 2011

Pitfalls with aspect technologies

Even though aspect technologies are very powerful. Especially to address cross-cutting concerns like transactions, it shouldn’t be used everywhere it’s possible.

The first part of this post consists of a simple example that uses AspectJ to return an unexpected value. The last part is about where aspects fits and where you should consider to avoid it.

A quote from the Spider-Man movie:

With great power comes great responsibility

This applies to some degree to aspect technologies too. Since it can change the behaviour of an application at compilation, startup or at runtime. Even without leaving a trace in the source code.

Implementing @Around advice

To get pre and post processing of calling any function, its good to implement @Around advice.

Consider the following Aspect with around advice:

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.util.StopWatch;

@Aspect
public class ProfilingAspect {

@Around("execution(* *(..))")
public Object profile(ProceedingJoinPoint joinPoint) throws Throwable {
StopWatch watch = new StopWatch();
watch.start(joinPoint.getSignature().getName());
try {
return joinPoint.proceed(); //calling the target method
}
catch(Exception e) {
throw e;
}
finally {
watch.stop();
System.out.println(watch.prettyPrint());
}
}
}

 

Corresponding config file:



<aop:aspectj-autoproxy />

<bean id="profilingAspect" class="ex7.ProfilingAspect" />
<!--some service class -->
<bean id="customerService" class="service.CustomerServiceImpl" />

Exception handling with AOP

The throws advice is executed when a method throws an exception.

Handling exception by this method saves us from writing repeating try-catch block again and again.

Consider the following java code:

//interface with method throwing exception
public interface BusinessInterface {

public void someBusinessMethod() throws BusinessException;

}
//class implementing it
import org.springframework.jdbc.BadSqlGrammarException;

public class BusinessComponent implements BusinessInterface {

public void someBusinessMethod() throws BusinessException {
//we are raising a different exception to see the aspect coming into action
//assume that you are connecting to the database and something goes wrong
throw new BadSqlGrammarException("","",null);
}
}


So now this business logic may throw exception, and it will be handled by Aspect.


So we have to write handler for this:


import java.util.Locale;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;

@Aspect
public class ExceptionHandler implements MessageSourceAware {

private MessageSource messageSource;

@Override
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}

@AfterThrowing(pointcut="execution(* someBusinessMethod(..))", throwing="ex")
public void handleException(JoinPoint jp, RuntimeException ex) throws Throwable {
System.out.println("Routine exception handling code here.");
System.out.println("Let's see who has raised an exception!");
System.out.println("===================================");
System.out.println(jp.getSignature().getName());
System.out.println("===================================");
throw new BusinessException(messageSource.getMessage(jp.getSignature().getName(), null, Locale.getDefault()));
}
}


Now if we want pre and post analysis of method, @Around advice will be handy for this.


Corresponding config file:



<aop:aspectj-autoproxy />

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="ex6/messages" />
</bean>

<bean id="exceptionHandler" class="com.xxxx.ExceptionHandler" />

<bean id="businessComponent" class="com.xxxx.BusinessComponent" />

Implementing @After and @AfterReturning advice

As we have done @Before, till now, it is also similar to that.

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class LoggingAspect {

@After("bean(*Service)")
public void log(JoinPoint joinPoint) {
System.out.println("log advice got executed after call to method : "+joinPoint.getSignature().getName());
}

@AfterReturning(pointcut="execution(* balance(..)) && args(acno)", returning="balance")
public void validate(JoinPoint joinPoint, long acno, double balance) {
System.out.println("validate advice called after successful return from balance method");
System.out.println("acno passed was "+acno+" and the balance returned was "+balance);
}
}



Spring config file :


<aop:aspectj-autoproxy />

<bean id="loggingAspect" class="ex5.LoggingAspect" />

<bean id="orderService" class="service.OrderServiceImpl" />

<bean id="customerService" class="service.CustomerServiceImpl" />

Named pointcut expression

Sometimes it happens that we may need same pointcut at multiple places. But since pointcut expressions are lengthy, it will be good if instead of repeating we can give a logical name to that pointcut and refer to it by logical name.

So for this we have to first create pointcut config :

package com.xxxx;
//
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class PointcutConfig {

@Pointcut("execution(public * service.*.*(..))") //This is a pointcut expression
public void serviceComponents() {} //This is a name given to the pointcut expression

@Pointcut("execution(* apply*(..))")
public void applyMethods() {}

}



Note that we @Aspect and @Pointcut annotations above.


When we write our own aspect we can simply refer to these method names in pointcut-config now:


import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {

@Before("com.xxxx.PointcutConfig.applyMethods()")
public void log(JoinPoint joinPoint) {
System.out.println("log advice executed for method : "+joinPoint.getSignature().getName());
}

@Before("com.xxxx.PointcutConfig.serviceComponents()")
public void timeLog(JoinPoint joinPoint) {
System.out.println("request for method : "+joinPoint.getSignature().getName()+" occurred at "+new Date());
}
}


In the config file, we have to define both beans:


<aop:aspectj-autoproxy />

<bean id="pointcutConfig" class="ex4.PointcutConfig" />

<bean id="loggingAspect" class="ex4.LoggingAspect" />

<bean class="service.OrderServiceImpl" />

<bean class="service.CustomerServiceImpl" />

Binding parameters to advice

A joinpoint object provides all the details required by the advice to perform any kind of operation.

Suppose we have to validate an order, and so we are writing our own aspect to get argument from pointcut - expression and perform validation. Example:

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

import service.Order;

@Aspect
public class OrderValidator {

@Before("execution(* placeOrder(..)) && args(order)")
public void validateOrder(Order order) {
//some order validation logic here
System.out.println("Just checking it out!");
}
}

In the config file we write:


<aop:aspectj-autoproxy />

<bean class="ex3.OrderValidator" />

<bean class="service.OrderServiceImpl" />


Pointcut expression

The most typical pointcut expressions are used to match a number of methods by their signatures. A common method based pointcut expression is something like

PCD(<method scope> <return type> <fully qualified class name>.*(arguments))


  1. PCD - PCD is pointcut designators. Spring AOP supports following pointcut expression -
    -- execution, with, this,target, args
    --Spring AOP also supports an addition PCD - "bean"
    --Of these, execution is most common
  2. method scope: Advice will be applied to all the methods having this scope. For e.g., public, private, etc. Please note that Spring AOP only supports advising public methods.
  3. return type: Advice will be applied to all the methods having this return type.
  4. fully qualified class name: Advice will be applied to all the methods of this type. If the class and advice are in the same package then package name is not required
  5. arguments: You can also filter the method names based on the types. Two dots(..) means any number and type of parameters.

Also these expressions can be chained to create composite pointcuts : && (and), || (or) , ! (not)


Some examples


the execution of any public method:
execution(public * *(..))

the execution of any method with a name beginning with “set”:
execution(* set*(..))

the execution of any method defined by the MyService interface
execution(* com.xyz.service.MyService.*(..))

the execution of any method defined in the service package:
execution(* com.xyz.service.*.*(..))

the execution of any method defined in the service package or a sub-package:
execution(* com.xyz.service..*.*(..))

any join point (method execution only in Spring AOP) WITHIN the service package:
within(com.xyz.service.*)

any join point (method execution only in Spring AOP) within the service package or a sub-package:
within(com.xyz.service..*)

any join point (method execution only in Spring AOP) where the proxy implements the AccountService interface:
this(com.xyz.service.AccountService)

any join point (method execution only in Spring AOP) where the target object implements the AccountService interface:
target(com.xyz.service.AccountService)

any join point (method execution only in Spring AOP) which takes a single parameter, and where the argument passed at runtime is Serializable:
args(java.io.Serializable)

Spring : Advice and its type

Any functionality that exists in an application, but cannot be added in a desirable way is called a cross-cutting concern.

That cross-cutting concern is called aspect-oriented programming (AOP). It deals with the functionality in applications that cannot be efficiently implemented with pure object-oriented techniques.

One of the core features of AOP frameworks is implementing cross-cutting concerns once and reusing them in different places and in different applications. In AOP jargon, the implementation of a cross-cutting concern is called an advice.

AOP frameworks allow you to define which advice is applied to which methods

Spring AOP supports following types of advices
Joinpoint is the point of execution of application, like method.
Spring AOP supports four advice types that each represents a specific scenario for advice implementations:
  • Around advice: Controls the execution of a join point. This type is ideal for advice that needs to control the execution of the method on the target object.
  • Before advice: Is executed before the execution of a join point. This type is ideal for advice that needs to performan action before the execution of the method on the target object.
  • After advice: Is executed after the execution of a join point. This type is ideal for advice that needs to perform an action after the execution of the method on the target object.
  • Throws advice: Is executed after the execution of a join point if an exception is thrown. This type is ideal for advice that needs to performan action when the execution of the method on the target object has thrown an exception.

Using annotation for configuring advices

We again take example of before advice.

Now we add @Aspect at the bean level. But on the method of the Aspect class, we can have annotations depending on what type of method or better advice they are. For before type advice we have @Before annotation.

Creating the aspect class


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {

//TODO: Try other pointcut expressions also as mentioned in slide no. 203-207
@Before("execution(public * apply*(..))")
public void log(JoinPoint joinPoint) {
System.out.println("common logging code executed for : "+joinPoint);
}
}


Now the bean class is quite cleaner, as we are annotation:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
>

<aop:aspectj-autoproxy />

<bean id="customerService" class="service.CustomerServiceImpl" />

<bean id="loggingAspect" class="ex2.LoggingAspect" />

</beans>


Here we are simply logging a simple text before entering the methods. Consider the case when we want to print about arguments.


This is where JoinPoint object comes into picture.


More about JoinPoint Object


Changing the before advice to take care of arguments , etc of the methods.


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect2 {

@Before("execution(public * apply*(..))")
public void log(JoinPoint joinPoint) {
Object proxyObject = joinPoint.getThis();
Object targetBean = joinPoint.getTarget();
Object[] args = joinPoint.getArgs();
Signature signature = joinPoint.getSignature();
//some logging code here
}
}



In the above xml file just change the class name of LoggingAspect to LoggingAspect2.


As the names of the method suggest :



  • this : The current executing object that has been intercepted

  • target : The target of the execution (typically our object)

  • args -  method args

  • signature - method signation of the joinpoint

One of the reason why aspectJ was adopted by the spring was because of v.powerful and easy to learn pointcut expression, which define where our aspects will execute.

Spring : Xml style configuration for pointcuts (Before advice)

The Aspect Class:

import org.aspectj.lang.JoinPoint;

//This is an Aspect class
public class LoggingAspect {

//This is an advice.
//Pointcut means where will this advice be applied.
public void log(JoinPoint joinPoint) {
System.out.println("common logging code executed for : "+joinPoint);
}

}

The configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
>

<!-- Tells the container we will be using AspectJ.
Also tells the container to use the proxy approach for executing aspects -->
<aop:aspectj-autoproxy />

<bean id="customerService" class="service.CustomerServiceImpl" />

<bean id="loggingAspect" class="com.xxxx.LoggingAspect" />

<!-- Aop config start -->

<aop:config>
<aop:pointcut expression="execution(public * apply*(..))" id="pointcut1" />
<aop:aspect ref="loggingAspect">
<aop:before method="log" pointcut-ref="pointcut1" />
</aop:aspect>
</aop:config>

</beans>


Note that we are using "aop" namespace in the xml to configure it to aspect class.

 


 

Writing the Aspect class

Consider our logging class. Which requires to log depending on what method we entered, left etc. whatever user requires. So we have to follow following steps:
  1. Write a class which will contain the common logging code. This is called Aspect.
  2. Either by xml or annotations we will have to configure a pointcut, to specify when(before, after, before return) and where(for all beans or only for a few bean or for a particular method pattern) will this aspect apply.
import org.aspectj.lang.JoinPoint;

//This is an Aspect class
public class LoggingAspect {

//This is an advice.
//Pointcut means where will this advice be applied.
public void log(JoinPoint joinPoint) {
System.out.println("common logging code executed for : "+joinPoint);
}

}
Methods of the Aspect class can be logically be called as advices.
We can use annotations or xml to configure the pointcut.
XML configuration for pointcuts
Annotation configuration for pointcuts

Chitika