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

Advertisements

More cool in Java EE 6 — JSF 2.0, Bean Validation

There’s definitely more cool stuff in JSF 2.0 that I didn’t get to last time — so let’s get right to it…

Annotations for Converters and Validators
The @FacesConverter and @FacesValidator annotations are nice little additions to the framework… they’re simple to use — you write your converter and validator classes in the same way as you always did, but instead of needing to crack open your already-way-too-large-faces-config.xml and look up the syntax for the converter tags, you can now rely on your IDE to help you out — just throw @FacesConverter on the class with the ‘forClass’ attribute, and it will automatically register that converter for all form fields of the appropriate class… it doesn’t get much easier than that, and of course you can use the ‘value’ attribute in the same way you used to use the ‘converter-id’ tag in the faces-config.xml, and then reference it in any of your pages…

Ok, you’re saying — so I get to add a line to my class file and take four lines out of an xml file — so what? But wait, there’s more — and this is my favorite part… throw an empty faces-config.xml file in your META-INF folder, and these converters and validators will automatically be registered for any JSF web app that includes this jar! This is a great mechanism to promote reuse — create a utility component that has a bunch of these files, and every one of your web apps can get them with a couple of lines in a Maven .pom file (or whatever it is you use for your builds)… I suspect it won’t take long for standard sets of converters and validators to become available in component libraries like RichFaces or IceFaces

Bean Validation
Speaking of validation, here’s where it gets interesting — with the new Bean Validation integration, it’s no longer necessary to think about validation just in terms of JSF… I personally believe that validation could be better approached as an integral part of a well designed domain model (think Domain-Driven Design here), so putting that logic in a JSF specific validator has always seemed awkward — likewise, adding a ‘validate()’ method that needs to be called while processing a form submit or just before persisting your object (in the case of a JPA Entity, for example) is just as awkward, if not worse… not only that, but many applications are more than just web apps — some have batch-processing or scheduled aspects to them which don’t have any exposure to JSF… using JSF validators in these cases would be a bit smelly, and duplicating the code is even worse — this is where Bean Validation comes in…

With the annotations in the javax.validation.constraints package, we can now annotate our domain fields with things like @Min, @Max, @NotNull, @Pattern, etc, so that the validation rules that our domain objects abide by are defined right along-side the fields themselves… there is, of course, an API available for evaluating the rules against a given object, but here’s where it gets cool — JSF and JPA both provide support for this automagically! That means whenever you have a domain object that is exposed through a ManagedBean in a form, the validation rules will be executed for you, and any failures are made available through the standard h:message tags! Not only that, but the validation can also be executed when you persist or merge your domain object via JPA, so batch-processing applications are covered as well — very cool…

A very similar incarnation has been available through the Hibernate Validation and Seam projects, but it is great to see this get worked into the standards… The basic constraints here are lean, but take care of most use cases — I have experimented with some simple custom validators, but am looking forward to getting into some more complex rules with multiple fields and see how it handles them…

Still more?
There’s still more stuff in EE 6 that I’d like to talk about, including the Facelets support and the new Composite Component stuff, but I need to do a little more fiddling with that — I came across the new ‘Behavior’ API as well, which looks like a slick way to make your components do what you want, as well as make them extensible… At some point, I’m going to get my hands on Web Beans, the new JPA 2.0 capabilities, Singleton EJB’s, Asynchronous EJB’s, etc — there is a lot of good stuff in this new spec, so stay tuned!

M

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

Web Beans Sneak Preview

In case you didn’t notice, Gavin King is offering a sneak preview of the Web Beans spec (JSR 299) so far in part 1, part 2, part 3 and part 4… It’s been a whole day since his last post, so it appears like now is a good time to put out some thoughts… These are in no particular, but will hopefully serve to continue the conversation to make the eventual spec as useful as possible…

  • Web Beans is not just about the web, as many people have already commented (including Gavin)… while I don’t necessarily need it to be brought to JSE, I believe a name change is in order…
  • If Web Beans becomes a generic Dependency Injection mechanism, then we would be left with at least three distinct DI systems in JEE — the Web Beans DI, the @EJB/@Resource DI from JEE 5, and the Managed Bean mechanism from JSF… something will need to be done to address this (please don’t say ‘Unified DI’, a la ‘Unified EL’ 🙂 )…
  • The @In annotation clearly comes from Seam, but there might be something more appropriate here — in Seam, there is also an @Out annotation, representing ‘outjection’… So far, Gavin hasn’t given us a hint of whether this will be around in Web Beans, but if not, then I think @In should become something like @Inject, @Bean, @Component, etc
  • The Guice influence appears to have replaced the String-based naming in Seam (i.e. — @Name(“myBean”) ) with annotations (@MyBean)… while this requires a little more code, it seems to be a good call — it should help prevent things like typo’s in the Strings causing NullPointerExceptions at Runtime…
  • Very flexible — follows the JEE5 pattern of defining a default configuration with annotations, but allowing it to be overridden or changed with an XML configuration… alternately, the XML configuration could be used as a central configuration file, as in Spring…
  • The various Component Types could be hugely useful for having multiple configurations for a single application, but I would like to see more ways of defining your components — for example, I like to be able to keep my system configurations in the app server itself, so when I deploy an EAR from test to staging to production, I can simply copy an EAR that has passed QA — if I have to change the web-beans.xml file, I can’t do this (unless there is perhaps a default that you could configure in your server)
  • I love the scopes, but Gavin mentions that the @ConversionScoped will be available from JSF managed beans, while request, session and application will be available from Servlets — what about JSF makes it the only thing that is appropriate for the conversation scope? Any reason it couldn’t be available to Servlets-based frameworks like Struts, etc.?
  • Could we reduce some of the annotation chatter with something like @In (scope=ConversationScoped, new=true)? Hmm… actually that ends up with more chatter — perhaps not 🙂

That’s enough for now… So far all I can say is “Great work guys!”… oh, and keep the previews coming!

M

Did Guice beat Sprint to the punch?

There’s been a lot of talk over the past few years that perhaps Interface 21 should push to formally make the Spring Framework a part of the JEE specs — it seemed like it might be possible with Rod Johnson officially declaring his support for JEE 6… well it looks like “Crazy” Bob Lee and the team behind Guice may have found a back door to get themselves into the party first — according to a new series of articles about the upcoming Web Beans, the new spec is actually influenced by a combination of Seam and Guice, rather than just Seam as previous reports had speculated…

This is not to say that Guice and Spring cover the same ground — Guice is strictly a product that supports dependency injection, while Spring does that and much more, but I find these articles interesting in that Google has apparently taken the JBoss approach to supporting the JCP — that is, create an independent product to fill a whole in the JEE specs, and then use the JCP to make that product into a spec itself (take a look at the JPA for a previous example)…

I personally think it’s a very smart approach — while it will perhaps create an opening for competitors to get into the market (more applicable when considering Hibernate and Seam than with Guice, admittedly), it opens up a clear opportunity to provide the first spec-compliant implementation (thus getting early adopters), and gives them a great opportunity to build and enhance their product while the competition is catching up (keeping the early adopters 🙂 )…

We’ll see where this goes, but so far it looks like an interesting spec — I see some potential for overlap between some other specs, but that may not be a bad thing…

M

More on rethinking JEE 5 patterns

Adam Bien often discusses the rethinking of JEE 5 patterns and best practices in his blog, and his latest entry discusses a replacement for the Value List Handler pattern that was prevalent in the J2EE 1.4 and earlier worlds called the Paginator. While I can’t say I love the name, the implementation is interesting — it’s really not much different than the old VLH pattern, except that it returns detached JPA Entities instead of Value Objects (hence the reason for the rename)…

What is interesting is that he has implemented the Iterator interface for this implementation, and each call to ‘next()’ returns a full page of JPA Entities… the code is really quite simple, and I’m sure it could benefit from further use of generics to make this a reusable Stateful Session Bean, but the fact that he is implementing an interface that every Java developer knows and uses pretty much every day (well, before JSE 5 came around, anyway), can only help people realize that perhaps now we can move closer to a real object oriented design… That is definitely a Good Thing… I urge people to take a look at the code in his Subversion repository (and some of the others in there are worth a look, too!)

M

Rethinking Best Practices

Ah, J2EE best practices — the community’s way of figuring out how to work with flawed technologies… You know, the Session Facade, Data Transfer Objects, etc. — they are ingrained in so many developers’ brains to the point of being second nature… It feels almost instinctual to design your system with them — putting your data over here in these classes, putting your logic over there in those classes…

Problem is, now that JEE 5 is becoming more common, those best practices are all wrong… ok, in most cases they won’t necessarily cause any harm (at least not of the magnitude of not following best practices about 5 years ago), but there are now better ways of doing things — we just need to learn what they are…

I’ll touch on a number of these in future posts, but I find that the area I have a lot of trouble with is getting rid of my habit to separate my data from my logic… the Session Bean/Entity Bean separation, in my opinion, is one of the more damaging patterns that was literally forced upon developers who went down the EJB path in the early days, and it’s a pattern that I’m not convinced is completely fixed yet… more on that in a later post…

Personally, my ‘toy’ projects are partially intended to get me thinking away from this — when it comes down to it, it’s all about trying to relearn those object oriented design principals, incorporate some newer techniques like Domain Driven Design, and just experiment in whatever way suits my fancy…

The first thing I do is put together my initial design in some form — either code, UML, a drawing, whatever… then I do it again, and look for specific flaws, like classes with only data and no behavior and vice-versa… of course, these scenarios aren’t always wrong, or even bad, but each time I go through this retrospective, I get a little better at identifying these issues to start with…

Do you have similar experiences? Spill the beans, let us know!