Life Codecs @ NamingCrisis.net

Ruminations. Reflections. Refractions. Code.

Apr 25, 2009 - software dev

Spring 2.5 + EJB 3 Integration

Yes, yet another post on the topic so talked about on the Web (like a year ago or so anyway!). This is mostly for my benefit and summary though – haven’t even written code to test it myself, but here goes. Spent a few hours exploring integration alternatives just now, basically EJB 3 DI is great, but a glaring thing that’s missing is injecting POJOs into it, which Spring does quite well – sure in both cases the “POJOs” are managed by containers, but hey, nothing’s perfect, yet. To summarise, here are the 2 major integration scenarios and solutions:

  1. To inject Spring Beans into EJBs (and bootstrap Spring app context(s) from within EJBs!) is simple enough, we use:

    Spring Docs, Chapter 18, EJB 3 Integration

    This actually handles bootstrapping (read up the doc on how it does it), which is tricky in EJB modules, since there’s no standard EJB context listener mechanism as there is for web containers. Many app server vendors do have EJB module lifecycle hooks/interfaces you can implement – but obviously they’re proprietary and make your app less portable, so I’d rather avoid them if I can, I still don’t see why this feature isn’t part of the spec… clearly there are use cases, and clearly since there are non-standard implementations, it’s feasible to do and define behavior for.

    • The other way around is a bit tricky, i.e. we now need EJB container-managed objects (e.g. entity managers, EBJs, resources, etc.) injected into Spring Beans in the XML file. In this case those resources need to be registered in the JNDI ENC (still figuring out EJB context vs. global) and in the Spring XML a JNDI lookup is done for the name it was registered with, and then injected to the relevant bean via a bean-ref. A ‘lookup-then-inject’ Spring XML config example can be seen here (note dataSource JNDI look-up and inject):

      Spring and JNDI (Tomcat or Jetty)

      Registering the container-managed objects in the JNDI can be done via EJB 3 interceptors, for example, a use case is having Spring-managed DAO beans, but EJB-managed Entities/Persistence Units: let the interceptor have an annotation

      @PersistenceUnit(unitName="bar", name=”barEntityManagerFactory”)

      – which receives the container-injected persistence unit and then registers it into the JNDI registry keyed by the name “barEntityManagerFactory”. The Spring XML config will need a bean created through a JNDI look-up of “barEntityManager”, and inject that in to the DAO Spring-managed bean.

      Lots of repetition up there! (Note I said it was for my benefit :P).

Now I can finally watch some Naruto!