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;