Sometimes you need to pass some additional / contextual data to the called EJB method. Because it’s a contextual data you don’t want to end in changing signatures of all your EJB methods just to add a single or few such parameters. It is possible to add context data using the SessionContext object.

Take a look at the following code example:

The result of this code execution is:

INFO: [myMethod] Method parameter: 2
INFO: [myMethod] Context parameter: Context hello!

A request made to MyService#myMethod(-) will be intercepted by MyInterceptor which will add some contextual data (ctx.getContextData().put(ctxParamKey, "Context hello!")) and invoke the actual EJB.

The EJB (just as interceptor did – with help of SessionContext) will recover the value saved by the interceptor and can use it right away.

If the parameter wasn’t set, the null value will be returned. So if you’d comment this code: ctx.getContextData().put(ctxParamKey, "Context hello!") you can expect following results:

INFO: [myMethod] Method parameter: 2
INFO: [myMethod] Context parameter: null

In this way you can pass the contextual data to your EJB methods without changing their signature. Just remember not to overdose with this feature, as it makes testing and auditing more difficult.

Did you like this? Share it:

7 thoughts on “Adding contextual data to EJB method

  1. Pingback: Adding custom context information to EJB method calls - Programmers Goodies

    • Hello Brooke,

      Yes, I guess that request-scoped @Produces and @Inject could do the trick for this use-case. I’m just thinking out loud here – what if you would like to set this contextual data basing on real-method parameters used to call it?

      Another difference I can think if is that contextual-data used SessionContext#getContextualData() and @Produces @RequestScoped is that request-scoped variable will be shared across all chain invocation and contextualData AFAIR will be only shared between interceptor and bean invocation (if your bean calls another bean it will not have this value propagated unless it goes through the interceptor once again.)

      That being said, I will agree that @Produces @RequestScoped / @Inject will be cleaner in this case.


  2. Hi Piotr,

    I am using Spring (SimpleRemoteStatelessSessionProxyFactoryBean) to invoke EJBs from xml file (with getBean). On other side beanRefContext.xml to inject beans into EJB to call business logic beans. EJB caller is in war where as actual EJBs are in EAR. I want to pass some information from WAR to EAR on each and every request via context (instead of method call). I new to EJBs (even spring-ejb integration). I am unable find the way to place the interceptor? Do I need to have same interceptor in both war & ear?

    Can you please help to have an idea with any example.


Leave a reply



<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>