Interceptor example in Java EE

Interceptor example in Java EE


@Interceptor
@MyInterceptor
public class MyInterceptor {
@AroundInvoke
public Object invoke(InvocationContext ic) throws Exception {
System.out.println("Entering "+ ic.getMethod().getName());
try {
// do your stuff before executing the method
return ic.proceed();
// do your stuff after executing the method
}
finally {
System.out.println("Leaving "+ ic.getMethod().getName());
}
}
}


@MyInterceptor
public class MyService {
...

public void myMethod() {
...
}
}

to enable the interceptor, either add an element to beans.xml like:


<interceptors>
<class>com.ardevco.MyInterceptor</class>
</interceptors>

or add a Priority annotaion


@Interceptor
@Priority(Interceptor.priority.APPLICATION)
@MyInterceptor
public class MyInterceptor {
@AroundInvoke
public Object invoke(InvocationContext ic) throws Exception {
System.out.println("Entering "+ ic.getMethod().getName());
try {
// do your stuff before executing the method
return ic.proceed();
// do your stuff after executing the method
}
finally {
System.out.println("Leaving "+ ic.getMethod().getName());
}
}
}

Interceptors enabled using @Priority are called before interceptors enabled using beans.xml, the lower priority values are called first.

Advertisements

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