Showing posts with label EJB 3. Show all posts
Showing posts with label EJB 3. Show all posts

Thursday, August 6, 2009

What's cool in Java EE 6 -- Singleton EJB's and Pruning

Well, with the all the excitement about the addition of JSR 330 Dependency Injection into the EE 6 platform, I figured I'd switch gears a bit and talk about the changes in a different spec -- this time, the EJB spec... Now, this spec is enormous -- 618 pages to be exact -- but luckily, we can ignore most of it! I mean seriously, who wants to read about EJB QL, 2.1 Client Views and the like... I'd rather dig into the meatier stuff, like...

Singleton Session Beans
We all know the Singleton pattern -- it may be one of the most well known designs patterns, and it's easy to understand... basically, if something's a singleton, then there's only one of 'em... ever... that means if you lose it or break it, it's gone for good... ok, that last part isn't true, and really the parts before that aren't quite true, either -- in most implementations of the Singleton pattern, folks conveniently forget to account for the fact that Enterprise applications often live in clusters, and instead they make singletons so that there is only one per virtual machine... most of the time this is fine -- they're often used for things like Service Locators, which were used back in the olden days of EJB 2 as a convenient way to do all the nasty JNDI lookups for EJB's...

Enter Singleton Session Beans... these are pretty much what you'd expect them to be -- an EJB that you can only find one of per JVM (the spec is specific about that last part, so really, they're only Singletons part of the time)... frankly, I was somewhat underwhelmed when I first heard of them, but they do add one interesting capability that I've needed on several EJB applications in the past, and have never had in an easy, portable way to pull off -- the ability to execute on application startup...

This can be achieved with a few simple annotations, like so:

@Singleton
@Startup
public class InitBean {
@PostConstruct
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void initializeSomeStuff() {
...
}



I know, lot's of annotations on that sucker, but it's pretty straight forward:
  • @Singleton -- defines this as a Singleton Session Bean... big surprise here, eh?
  • @Startup -- this is an indication to the app server that this class must be created and initialized at application startup, and yes, the spec uses the 'must', so there's no soft language here
  • @PostConstruct and @TransactionAttribute -- these are the old tags that we all know and love...
Anyone who's read this blog before may notice a hidden gem in here that makes all of this worthwhile... I'll give you a hint -- go read this entry on @PostConstruct... yes, that's right, this is a Transactional @PostConstruct method... and it will work! They got this one right when they wrote the EJB 3.1 spec, in that it guarantees that @PostConstruct methods will obey your @TransactionAttribute attributes! Now if only they would extend this capability to all EJB's, we'd have all of our problems solved! Ok, perhaps not all of them...

So anyway, you can do pretty much whatever you want in here, including initializing 3rd party systems, creating timers, sending email, truncating all of your database tables, etc... what most intrigues me, though, is data bootstrapping, similar to what you get with the Grails Bootstrap class:

...

@PostConstruct
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void setupUserData() {

List expectedUsers = getExpectedUsers();

for (User u : expectedUsers) {
User found = em.find(User.class, u.getId());
if (found == null) {
log.info("Persisting user "+u.getUsername());
em.persist(u);
} else if (!found.equals(u)) {
log.info("Updating user "+u.getUsername());
em.merge(u);
} else {
log.info("No need to update user "+u.getUsername());
}
}
}

...


In other words, this Singleton will ensure that your standard set of users will always be available upon application startup -- if this is something you want only in a development environment, you can configure each machine with environment information via JNDI, System properties, or a configuration that is set in your build so that it only takes these actions on a development environment -- it is a great way to ensure a consistent development environment across your team...

A Word about Pruning
Ok, this is, by far, my favorite feature of Java EE 6 -- and it's not even a feature! That's right, we're finally going to be able to actually remove some of the stuff that's been added to Java EE over the years! This could include a wide variety of things, but just think -- some day in the near future, you won't have to sift through details about Entity Beans, outdated communication protocols like JAX-RPC, EJB Home interfaces... instead, it will all be gone! Unfortunately, this day hasn't come just yet -- they're just telling us that they're planning to do it some day, but at least it's a step in the right direction... now I have to wonder -- will Java EE 7 actually be a smaller spec than EE 6? Now that would be impressive :)

In the meantime, you can get a little hint of the pruning goodness by taking advantage of the new Web Profile -- this is a nice customization of the spec that removes a lot of the stuff that most folks don't use anyway, but that is still pretty useful in some cases... unfortunately, you still do have to thumb past all of the extra stuff if you decide to go diving into the spec documents...

Conclusion
It seems odd to me that it took so long for Java EE to standardize such a simple, but useful piece of functionality as startup logic -- to me, this is more important than the fact that this EJB is a (kind-of-)Singleton! Sure, I've always been able to do this through an eagerly loaded Servlet, or with WebLogic or JBoss specific code, but the Servlet solution is just plain weird if I'm not acting upon my web container, and this is obviously more portable than an app-server specific piece of functionality... the above example just seems a little less... dirty to me :)

But who am I to complain about a nice new feature :)

M

Tuesday, September 25, 2007

Can EJB's be used as more than facades?

In the 'good old days' of EJB 2.x, we were trained to design systems such that the 'facade' was created with EJB Session Beans (usually stateless), while everything behind it could be regular Java classes... there were exceptions, of course, as it may have been necessary to access an occasional EJB from behind the facade if it was located remotely, it had different transactional requirements, or if we were simply dealing with a third party component, but for the most part, this is the mantra that we followed... at some point, Spring came along and made us realize that we didn't really need the heavy-weight EJB's at all, so we threw them out all together... and there was much rejoicing...

Now we have EJB 3, which improves on the old spec in pretty much every way... While I won't suggest that EJB 3 will be usurping Spring usage anytime soon, there are certainly places where EJB's are now at least as good a design choice, if not better... The problem is, we lose the nice Dependency Injection that Spring gives us in these cases...

But hold on -- take a step back and look at your design... if you're designing your app with the old Session Facade in mind, the previous statement is certainly true -- you can't use DI to assemble your domain objects beyond the outer layer -- but I think I can make a case for bringing EJB's back into the heart of your application...

Let's look at reason number one for the original Session Facade -- creating a Session Bean used to be tedious, and it caused us to alter the way we program (ok, reasons 1 and 2, I guess)... but this isn't true anymore -- it's no longer tedious to create a Session Bean -- you just add '@Stateless' to your class... it's also no longer necessary to alter the way we program, at least in many cases -- we don't have to work with Service Locators or Business Delegates, we don't have to manually look anything up in JNDI -- all we have to do is add '@EJB' or '@Resource' to our member fields...

So by allowing any and/or all of our domain objects to be EJB's, we gain the Dependency Injection benefits of acquiring other resources as well... for example, if your Repository or DAO is created as an EJB, you can inject your EntityManager into it quite naturally...

Of course, it's not a perfect scenario... there's some overhead involved in an EJB method call -- security and transaction management, for example -- that could potentially cause your app to be slowed down a bit... personally, I'm not convinced that the slight performance decrease would outweigh the benefits you get from the very natural DI system, but that's purely my opinion... If anyone has any hard data on the kind of performance profile you'd be looking at, I'd be interested in seeing it... additionally, I believe it would be possible for a container to intelligently optimize the calls out in many cases -- I'm not sure how much of this is technically allowed by the spec, but it should be extremely quick to check for an existing, open transaction, for example...

As an aside, the recent Web Beans sneak previews from Gavin lead me to believe that we will be able to get the benefits that I describe above without the drawbacks -- of course, Web Beans may end up signaling a return to the Session Facade for transaction management, while our Domain objects are assembled with the Seam-and-Guice-like Dependency Injection, but hey, it's always good to question what we 'know' occasionally, right?

So is it time to throw away our prejudices against EJB's? I think for a lot of us, it's at least time to reevaluate them...

M

Wednesday, July 11, 2007

JEE and Spring

How are people using JEE 5 and Spring these days? There's a lot of overlap in the technologies, obviously, and there are reasons to use both, but I'm interested in those using them collaboratively...

I've seen some articles about how one can integrate the two by accessing a Spring ApplicationContext from within an EJB 3 Session Bean, but none of them seem to address the fact that the two have different life cycles -- using dependency injection within a Session Bean's PostConstruct method could cause some unexpected problems if you're using Spring's prototype scoping... there's no guarantee that the PostConstruct will be called for each invokation, but only when the bean is originally created...

Has anyone out there dealt with this? Would it be possible to create an 'ejb' scope with Spring's new customizable scopings?