dagblog.
← Archive

EJB 3.0, Interceptors and Spring


Yesterday I read Pavel Kolesnikov's note about
the second EJB 3.0 Early Draft with interest. I hadn't meant to
get into it at all, but I couldn't resist reading the discussion on TSS.
A debate about annotations versus XML configuration caught my eye, but I'll leave that for next time. It's no secret
that JBoss has been busy with EJB 3.0 and has been quick
to put out previews. As someone put it, JSR 220 is the JBoss camp.

The post JBoss EJB 3.0 Preview 3 Is Out appeared on TSS today and piqued my curiosity.
I couldn't resist a quick look at the tutorial.
I hadn't read the specification, but interceptors caught my attention. I'll borrow Pavel Kolesnikov's words here.

Interceptors (JBoss application server users and AOP fans probably have an idea already). An interceptor is either a method that is inserted into a business method call, or a class whose methods act as interceptors for the target class. Here the target class can only be a session or message-driven EJB component.

The tutorial devotes a good-sized section to interceptors
and shows what they're for. To me they look like a welcome move toward AOP. I can't resist a small dig, though.
We've had this in the Spring application framework
for a long time, thanks to AOP. Shall we look at a quick example?

Interceptor

package my;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class TracingInterceptor implements MethodInterceptor{    

public Object invoke(MethodInvocation invocation) throws Throwable {
long start = System.currentTimeMillis();
try{
invocation.proceed();
}finally{
long time = System.currentTimeMillis() - start;
System.out.println("Invocation time: "+ time + "ms");
}
}
}
We'll put the interceptor defined here, essentially an aspect, into the application context
(Spring's configuration).

Advisor

To use this interceptor, we also have to define an advisor
that determines whether the interceptor applies. Suppose we want to attach our
interceptor to the getFoo method. We'll use one of the standard advisors Spring provides,
again configured in the application context.
getFoo

Attaching the Interceptor to a Class

Now we'll attach the interceptor declaratively to the object we want, Foo in this case.
my.IFoo



myAdvisor
For completeness, here's the Foo object itself, along with its interface.
package my;
public interface IFoo{
public Object getFoo();
}
package my;
public class Foo implements IFoo{
public Object getFoo(){
//do something
}
}
If you prefer annotations to declarative XML, you can use those too. See Spring Source Level Metadata Support.

Medium version

Related articles

Related CZ Podcast episodes