JBoss 5 and AOP: how-to guide to add AOP aspects to your application


A quick example on how to add an interceptor to your application, for example to log or profile methods invocation:

  • Add “-javaagent:pluggable-instrumentor.jar” into JAVA_OPTS variable of file run.bat (or run.sh)
  • Edit \conf\bootstrap\aop.xml and set the element enableLoadtimeWeaving to “true” and add to the element include the package you want to instrument
  • Create the jboss-aop.xml in the META-INF directory of your package like this:
<?xml version="1.0" encoding="UTF-8"?>
<aop xmlns="urn:jboss:aop-beans:1.0">
  <interceptor name="Int" class="com.xxx.LogInterceptor"/>
  <bind pointcut="execution(* com.*->*(..))">
    <interceptor-ref name="Int"/>
  </bind >
</aop>
  • Create the Interceptor class:
import org.jboss.aop.advice.Interceptor;
import org.jboss.aop.joinpoint.Invocation;
import org.jboss.aop.joinpoint.MethodInvocation;
public class LogInterceptor implements Interceptor {
@Override
public String getName() {
  return "LogInterceptor";
}
@Override
public Object invoke(Invocation invocation) throws Throwable {
  long time=System.currentTimeMillis();
  try {
    return invocation.invokeNext();
  } finally {
    time=System.currentTimeMillis()-time;
    if (invocation instanceof MethodInvocation) {
      MethodInvocation mi = (MethodInvocation) invocation;
      String clazz="";
      try {
        clazz=mi.getTargetObject().getClass().toString();
      } catch (Throwable e) {
        // TODO: handle exception
      }
      //Here you can use a logger to log time and method name
    }
  }
}

References:

Advertisements

One Response to “JBoss 5 and AOP: how-to guide to add AOP aspects to your application”

  1. Ghosh Says:

    I am behind a logging aspect which intercepts each method under “com.mycompany” package and its sub-packages. Which is similar to your
    sample application.
    I tried with your example but couldn’t get it running mainly because of the expression “execution(* com.*->*(..))”. r u sure that works? I tested that in a standalone application.

    I am trying hard but unable get the pointcut expression right. Please suggest.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: