Thursday, May 15, 2008

How can several SLSBs share the same interface?

Here is a tip that I wasn't able to find anywhere (maybe I didn't look hard enough).

It may be a rare situation that you would have a large number of session beans (EJB3 session beans) that need to share the exact same interface. And probably, there are several reasons why it could be argued that it is a bad idea anyway.

But, I had about twenty-five timer beans that only needed to expose the same single method 'setSchedule' - so that they could be scheduled.

When I first created all of these timers, I made separate interface classes for each of them so that I could easily access them like this:

@EJB private TimerInterface1 timerInstance;

That wasn't so bad - Even though every timer class that I created ended up having its own interface that was exactly like all of the others.

When I got up to twenty-five though - I thought there must be a better way.

And I finally found it. So now, I only have one interface class for all of the timers and here is how the particular bean that is needed gets declared and accessed. As a note, I happened to be using stateless session beans - the same should work for stateful.

(declaring)
@Stateless
public class ParticularBeanImplementation implements GenericInterface {


(accessing)
@EJB(beanName="ParticularBeanImplementation") private GenericInterface specificInstance;

I can't believe it took so long for me to find how to do this.

No comments: