One of the more interesting things I'm picking up in my new job is EJB3. My background is almost entirely in non-JEE technologies--Spring, Hibernate, and everything built around those. EJB's purpose is very similar to Spring's, and the two have functionally converged over time to the point that annotation-based EJB3 is very similar to annotation-based Spring.
The aspect I'm looking at right now is EJB's dependency injection system. EJBs may declare fields with an @EJB annotation. This informs the EJB container that that field should be populated with an EJB which implements the class of that field immediately after the bean with the field is instantiated.
One thing to be aware of when doing this is that multiple EJBs may implement a given class. I'm not sure if the container's behavior is prescribed by the JSR or if it's just per-implementation, but JBoss uses multiple tiers which it analyzes. Multiple EJBs implementing the class in a given tier results in an exception, but if you have one in the "closest" tier and another in a different tier, you should be fine.
In thinking about the problem, it seems to me that multiple instantiations of an EJB interface should be relatively rare. For the most part they represent distinct pieces of the system which should be well encapsulated--having multiple implementations suggests to me that the responsibilities of the bean are not properly defined and the functionality which differs should be analyzed to determine whether it should be broken up, and I suspect that it probably should.
Regardless, it may prove necessary in some cases, and in those cases one can disambiguate between the beans with a string called a JNDI name. The JNDI name is passed to the EJB annotation. This should be unique within the system, so collisions at this level are illegal.
One of my coworkers is of the opinion all @EJB annotations should include this JNDI name. However, based on my thinking above, I believe the actual value of this to be incredibly small, and doing it just introduces overhead we don't need, and based on the YAGNI principle, should be avoided until it actually becomes necessary. We'll see how this is resolved.
Post a Comment