Archive for the ‘jboss’ Category

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

31/12/2009

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: