Injecting EJBs into Struts 2 Actions

I think Sun/Oracle has done a great job of simplifying the EJB mess. I’ve been integrating Stateless EJB3 beans with the Struts 2 layer recently and it’s been working pretty well. To create a stateless EJB, you simply annotate the class with @Stateless. Nothing else is needed! No XML configs, no Remote interfaces, NOTHING!

Then when you want to use the EJB, just inject it. For any normal container managed classes you can inject a EJB3 bean by using the @EJB annotation. For example, if you wanted to inject the MyEjbLocal bean, just tag it with @EJB like this:

@EJB
MyEjbLocal myEjbLocal;

However, I wanted to make use of EJBs in my Struts 2 actions. Using the above method doesn’t work because Struts Actions aren’t managed by the Container/App server. You could perform a Initial Context look up everytime but that seemed to be a silly work around.

Instead, just write your own annotation that performs the lookup and then take advantage of the Struts 2 Interceptor stack. In your struts.xml config, you’ll need to define a new interceptor that points to your custom class:

<interceptor name="ejb3" class="com.opensymphony.xwork2.ejb3plugin.InjectEJBInterceptor"></interceptor>

You can find this code freely available on the web or contact me if you would like full src code. This interceptor defines an annotation like this: @InjectEJB.

Then make sure its added to your struts stack. Note ‘defaultStack’ is built into Struts 2:

<interceptor-stack name="new.stack">
  <interceptor-ref name="ejb3" />
  <interceptor-ref name="defaultStack" />
</interceptor-stack>

Finally, inject your new interceptor stack into your actions:

<action name="index" class="com.usps.TestAction">
   <interceptor-ref name="new.stack"/>
   <result name="success" type="tiles">index.tiles</result>
</action>

Now you can use the @InjectEJB annotation in place of @EJB in any of your Struts Actions!

@InjectEJB
MyEjbLocal myEjbLocal;
Advertisements

2 thoughts on “Injecting EJBs into Struts 2 Actions

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