Thoughts on JSR 330

I’m not sure what to think about JSR-330 — what do you think?

A quick caveat before I begin — I’m playing devils advocate here, so I have no idea if I believe any of the gibberish that I’m about to write 🙂

On one hand, I think it’s Mostly Harmless… CDI/JSR-299 is obviously the default implementation of the spec, and perhaps having a very small portion of the DI capability abstracted so that we have the choice to use another framework if we want isn’t necessarily a bad thing (even if standardizing injection targets isn’t exactly ground breaking value) — after all, if it weren’t for those ‘outside’ framework writers, we might not have gotten EJB 3, and all the improvements that came along with Java EE 5… perhaps JSR 330 is a way to bring those folks inside of the Java EE fold, so it’s not another three years before the standards catch up with the private innovation

On the other hand, is it at all likely that an application would be able to just replace the DI capability of CDI with, say, Spring or Guice, but still use the contexts, interceptors, extensions, etc? After all, Dependency Injection is actually a pretty small part of what the CDI spec provides… Perhaps, if one were to write a CDI Portable Extension that basically vetos all bean discovery, and instead uses one of the other libraries to do the injection, but that seems like a stretch to me…

What seems more likely is that another implementation would simply not use CDI, which can easily be done by not providing a beans.xml file, and using some other mechanism, like the Spring WebApplicationContext — in that case, is there value in what the JSR-330 spec provides? Has the addition of this spec, which provides little value in-and-of itself incorporated too much confusion?

My original instinct was that it’s a good addition to the Java EE fold, but I’ve heard a few voices of opposition (including from those who don’t have a big stake in the outcome)… now I think, perhaps, that I could take it or leave it — I haven’t been convinced that it’s destructive, but I’m also not convinced that it’s worth it 🙂

What do y’all think?


CDI and Declarative Transactions…

Ok, so since I’m already on the books for declaring that CDI/JSR-299 will become the dominant framework of the Java EE standards, while pushing EJB 3 off to the side, let’s start to figure out how this could work… I don’t think too many people would argue that the number one reason for using EJB 3.x Session beans are the Declarative Transaction support — that is, being able to create and commit a new Transaction around a method call by annotating it with @TransactionAttribute(TransactionAttributeType.REQUIRED) — and compared to the boilerplate code that needs to be put in place to do it programatically, it is indeed a pretty nice feature…

So how can this be done in CDI? Simple — with Interceptors… CDI actually reuses the interceptor support from EJB 3, but it takes it a step further — it allows you to use a custom annotation to bind your code to the interceptor definition in a pretty slick way… but first, consider the following interceptor, which might be the most basic implementation of Declarative Transactions:

//import removed...

@RequiredTx @Interceptor
public class RequiredTransactionInterceptor implements Serializable {
private UserTransaction utx;

public Object openIfNoTransaction(InvocationContext ic) throws Throwable {
boolean startedTransaction = false;
if(utx.getStatus() != Status.STATUS_ACTIVE) {
startedTransaction = true;

Object ret = null;
try {
ret = ic.proceed();

} catch(Throwable t) {

throw t;

return ret;

You’ll notice that most of this looks familiar — we’re not implementing any particular Interface, we can use any old name for our wrap-around method, we use the @AroundInvoke annotation to indicate which method is to be used for intercepting, and how it’s used, etc. The only thing new here comes on the first line — the dual annotations of @RequiredTx and @Interceptor… so far this is wicked easy!

So what the heck are those annotations? Well, the @Interceptor annotation is part of the javax.interceptor package, and was added as part of the CDI spec — clever how they snuck a new annotation in but didn’t put it under any CDI-specific package, eh?

The other annotation is one of my own, and when used in concert with @Interceptor, it acts as the ‘binding definition’ of the interceptor — you can then put the @RequiredTx annotation on any method or class of any CDI bean, and it will be as if you’ve annotated an EJB with ‘@Interceptors(RequiredTransactionInterceptor.class)’, only not as wordy (and why would you write a transactional interceptor that mimics the EJB usage, and then use it on an EJB?)

Without further ado, the definition of our annotation:

//more imports removed...

@Target({ElementType.METHOD, ElementType.TYPE})
public @interface RequiredTx {

Not much here — the only thing you may not have seen before is that InterceptorBinding annotation, which simply declares that this annotation is used to bind an interceptor to a method or class… simple — but how is it used? This is the cool part — just annotate any old CDI bean with this, and you’re good to go — like this:

//yep -- no imports here either...

public class UserGetterer {
public User loadUser() {
\\Do some fancy JPA loadin' here

Load that up in your webapp, point your fancy JSF 2.0 preRenderView event to “#{userGetterer.loadUser()}”, and voila — you are loading your data in a transaction… sweet!

Doh — almost forgot
What’s that? It didn’t work? Crap… oh wait, one last thing — we need to enable our interceptor… This part is easy to forget, but easy to do — you need to add an element to your beans.xml… (you did add the beans.xml file, right?)… try this:


Yeah, I know — it feels kind of like we’re exposing your implementation detail by asking the user to enable the interceptor instead of the annotation… kind of annoying, but I can deal with it… another thing to note is that if you pack your interceptors into a shareable library file, all other library files in your application will still need to do this, even if you enable it in your .jar file — that’s because there’s no concept of a global interceptor in CDI, but to be safe, each library is forced to enable all interceptors in use, so that they can enforce the ordering of interceptors in a very intuitive manner… I can accept this reasoning simply because they have defined it, rather than letting it be an undefined mess, so again, it’s more of annoyance for me — hopefully there will be other options in the future… (Note – due to a bug in the current version of Weld, Glassfish and JBoss will both have a problem with this — the work around at the moment is to include all of your definitions in one library file, or your .war file directly)

Sum It Up
So there you have it — a bare minimum implementation of Declarative Transaction support for CDI that can be applied to both classes or methods in less than 40 lines of code… easy, and very reusable! It would be similarly easy to implement for the other EJB TransactionAttributeTypes (SUPPORTS, REQUIRES_NEW, etc), although there is some coordination to be done to support putting one annotation on a class and another on a method without having them tripping over each other…

All in all, it provides a very straight forward programming model that is at least as clean as the EJB 3.0 model — cleaner in many ways, actually, as you’ll have @RequiredTx instead of @Interceptors(RequiredTransactionInterceptor.class), better context management with @RequestScoped, @SessionScoped and @ConversationScoped instead of just @Stateful, and much better integration with JSF… Plus, you’ll have the benefit of being able to customize it if you need to, adding support for things like timeouts, isolation levels, or custom logging… very nice, indeed!


CDI/JSR-299 preparing to marginalize EJB… again…

Whew, it’s been a while since I’ve started looking at what’s new in Java EE 6, partially because I’ve been fiddling with the newest addition to the Java EE portfolio — JSR-299, aka CDI, f/k/a Web Beans, and this one could be big… Let’s start with a bang — CDI will eventually push EJB to obscurity… yeah, big statement, I know, but here’s why I believe this will happen:

  • CDI has the potential, I believe, to provide all of the most commonly used services that the EJB spec provides, and let’s face it, this mean transactions, timers, asynchronous process with MDB’s, and now Singleton Startup beans. It does not mean remoting, instance pooling, and most certainly not any of the old CORBA crap 🙂 — also note that I’m not referring to JPA here at all, now that it has been removed from the EJB spec (as it should be!)
  • The CDI spec comes in at 98 pages.
  • The EJB 3.1 spec (PFD version), comes in at 618 pages — yikes!
  • The CDI spec is far more flexible than the EJB spec, allows for more interesting and transparent customizations, and is built specifically to support extensions.
  • CDI’s mechanisms for injection (which it inherits from JSR-330, thanks to Rod and Bob!), is more consistent, inclusive and unified than EJB’s/JEE 5’s.
  • CDI’s inclusion of Stereotypes provides an awesome mechanism to create a lightweight framework, without directly exposing any CDI api to the end user.
  • CDI’s context support is very extensive, and is far more complete and useful than EJB’s Stateless and Stateful beans. Plus, it finally gives us a standard between Request and Session scoped.
  • CDI’s integration with JSF is far better than EJB’s (ever had a manually remove a Managed Bean from scope because its’ Stateful bean has completed its’ lifecycle? Come on!).
  • CDI’s event mechanism provides for extensibility and easy, lightweight asynchronous processing.
  • There’s no such thing as CDI Lite 🙂

That’s not a short list, and admittedly, it’s very early to make claims like this… after all, the spec has just finally been approved, we have yet to fully see the quality of the implementations (three that I know about, Weld, CanDI and OpenWebBeans — hey, how come they got to keep the name!?), we have yet to see how the closed-source vendors will handle it, etc., but when it comes down to it, the CDI spec is simply better suited for POJO-style development, using Object Oriented core design principals, and it was designed specifically with this in mind… Contrast this with EJB, which has over a decade of cruft to carry along with it, and actually prevents the use of OO techniques altogether (historically more-so than today, but it’s still an issue), and I think the future becomes fairly clear… All-in-all, I see it as great news for the Java EE platform…

One final caveat, though — EJB has risen from the ashes before, specifically with the 3.0 version… if the vendors still feel the need to continue to push EJB, then who knows what we’ll see 🙂

Nice NetBeans/Maven integration

Just found this pretty cool feature in the latest 6.8 M1 release of NetBeans… when working with Maven project, you can, of course setup dependencies on other Maven libraries, but ‘native’ NetBeans projects don’t have this ability — you can only setup dependencies to other Projects, to ‘Libraries’, and to random .jar files… however, NetBeans now has the ability to create Libraries from Maven libraries, and then use those in any projects… check this out…

Open the Maven Repository Browser (Window -> Other -> Maven Repository Browser if you haven’t seen this before), and find a project you’re interested in by either browsing or searching… once you’re here, right click on the version you want, and select ‘View Details’, like so:

This brings up the details of the .pom file, which has all sorts of good stuff, but the cool part is the icon of the stack of books in the upper right — click this, and it will automatically download the project and set it up as a NetBeans Library, for use in any project… pretty sweet!

Of course, this may have been here all along — if anyone knows of a prior version of NetBeans that this works with, chime in!


What’s cool in Java EE 6 — JSR 330?

Hey, interesting timing on this one, given my previous two entries this week — a blog entry just caught my attention indicating that Java EE 6 is getting a late entry in the form of JSR-330 — Dependency Injection for Java… I noticed this spec when it was first announced back in May or so, and immediately thought “Oh boy, a direct competitor to Web Beans! This is going to confuse things!”… don’t forget, Web Beans was renamed at some point to ‘Contexts and Dependency Injection for the Java EE Platform’, so these specs appear to be very similar at first glance…

So what’s going on here? I haven’t the foggiest, but it is interesting that JSR-330 is headed up by Bob Lee and Rod Johnson, the masterminds behind Guice and the Spring Framework — certainly a pair of heavy hitters in open source Java land… I seemed to recall that Bob Lee had some involvement with Web Beans as well, but he is not listed on the JSR-299 expert group, so it may well have been my imagination…

Another interesting blog by Roberto Chinnici has a little more detail, giving some background behind the decision and indicating that Web Beans will be modified to use the JSR-330 annotations — I’m quite interested in his last sentence (well, second to last — the “Stay tuned!” doesn’t count), which is a vague reference to reconciling Web Beans with the rest of the spec, especially in regards to Managed Beans… I was actually wondering if anything was going to happen here — early indications are that a Managed Bean can become a Web Bean by replacing the @ManagedBean annotation with @Named, so why have both, especially if both are included in the Web Profile? At first glance, they seem to both be extremely similar, with Web Beans simply adding a few pieces of functionality — more digging needs to happen on my part here, for sure…

So what the heck does this mean? Well here’s my initial impression:

  • This appears to be a good thing — one of my pet peeves with the EE spec process is the tendancy to simply not make some hard decisions. This appears to be a pretty bold move, and may have prevented a situation where we have three distinct DI mechanisms in the standard (the original @EJB/@Resource/@PersistenceContext, the Web Beans @Current and @BindingType, and the JSR-330 @Inject and @Qualifier annotations)
  • It is an interesting turn of events for SpringSource, which has appeared poised to become a possible implementation of the Web Profile with their new tc Server, or even a full fledged app server with the dm Server — this certainly seems to indicate the direction they plan to go
  • Gavin King must be pissed :)… ok, so I have no idea about this one, but it will be interesting to see how it turns out anyway…
  • We may end up with a slightly more cohesive web framework if, for example, Managed Beans and Web Beans are combined, but we have yet to see what direction this is going to go — certainly interesting! If I’m correct in my understanding of the similarities between the two types of objects (and I may very well be incorrect at this point), one could make do by always using the Web Beans version, which makes @ManagedBean dispensable…

So my ears will definitely be open to movement in this space… nothing like an 11th hour addition to the spec which may cause changes in two or more existing and ‘finalized’ specs to make things interesting!


What’s cool in Java EE 6 — JSF 2.0

Howdy — been a while since I’ve been around here, but I’ve been fiddling with some of the new technologies in Java EE 6, and figured that this is as good a place as any to start to talk about them :)…

First off, I’ve been working with NetBeans 6.7 and Glassfish v3 Preview (look here for info on how to get the two to work together)… I have plenty of experience with NetBeans, but less with Glassfish — ever since it took forever for JBoss 5 to come out, it has been my App Server of choice for ‘fiddling’ with technologies… it’s really quite impressive, and seems to be one of the places for early access into new technologies…

Anyway, there is plenty of new stuff in EE 6, and one of the areas that shows a ton of improvement is JSF 2.0… Where to start?

So long, faces-config.xml!
Well the most obvious starting point has to be the Annotations… in old-school JSF, any sizable application needed to have every Managed Bean registered in an XML file, which is fine for the smaller examples, but quickly gets to the point of needing to use an appropriate tool to decipher and organize it… Thankfully, this has been replaced by a single (sometimes two) annotations directly on the class, like so:

public class LoginBean {


And no discussion of XML in JSF would be complete without mention of the navigation… not only was this too verbose, but it never struck me as an appropriate place to store navigation information — after all, I already have my Managed Beans and XHTML pages (we’ve all been using Facelets for years now, right?) — why do I need to look in a third place to configure what page an action in a page takes us? Again, manageable, but a bit smelly…

Once again, JSF 2.0 makes an improvement here by allowing us to return the names of our views directly from our Managed Beans — so instead of returning “Success”, and then having to indicate what that really means in another file that’s too big as it is, I can just return “success.xhtml”, and the page will be found for me (in fact, I believe a return of “success” would have the .xhtml added for me, but for some reason the explicit version seems more palatable to me)… and if I want this to be a redirect, it becomes “success.xhtml?faces-redirect=true” — admittedly a bit awkward, but simple and easy to remember…

Ok, this is the really big one — frankly, I am stunned that it has taken, what — 8 years for JSF to add this feature natively (I apologize if that number is wrong, I’m not up to looking up the JSF history right now)… in the past, I have created my links with standard html ‘<a href' tags and used a @PostConstruct tag in my Managed Bean to load whatever data I needed, but frankly it's a hack, and the fact that @PostConstruct operates in an undefined transactional state forces you to jump through hoops, not to mention that circumventing the JSF View lifecycle can be difficult at times… In fact, I was actually quite concerned in the later days of the spec development, because it appeared that this feature was not being taken seriously by the spec group — that Ajax and skinning were more important features than perhaps one of the most basic features of any browser… blog entries by those with ‘inside information’ were coming out as late as early 2009 that seemed to gloss over the demand for bookmarkable features, but thankfully it made it in at the last moment… whew!

There are a couple of items that are important here, but the basic idea is that any page that can be bookmarked (and that requires info from the query string) uses three new tags — f:metadata, to define metadata for a view, f:viewParam, which can take a parameter from the query string and store it in a variable (including conversion, validation, etc), and f:event, which can be used to register an event listener on the new PreRenderViewEvent — it might look something like this:

Alternately, you could simply use the old c:set tag to set the variable in the page, however this appears to store a copy of the variable, which doesn’t work out well if you are later editing or modifying it…

Finally, to create a link to your new-fangled page, there is also the new h:link tag, which follows the same direct navigation rules mentioned above, and that can support the f:param tag to easy include parameters — easy peasy!

To Be Continued…
Ok, this turned out to be longer than expected — I still want to talk about PDL, Events, Annotations for Converters and Validators, Bean Validation integration, Web Beans integration, and plenty more, but that will have to wait for a later date…

The bottom line is that yes, JSF is a viable web framework — it has had its’ problems historically, but the latest version seems to have addressed them quite effectively, and there are plenty of component libraries out there like RichFaces, IceFaces, etc., that can make your apps look and operate great… Hopefully it can shed some of its’ poor reputation (much of it deserved, some of it not) — it’s definitely worth a look!


Java EE reminds me of the government…

Don’t get me wrong — I like Java EE 5… I’m especially a big fan of being able to make a living working with it, but sometimes you run into some weird things that just make you scratch your head…

The government analogy comes from the fact that the @PostConstruct annotation cannot be used in conjunction with a transactional or a security context… It’s almost like a bunch of possibly well meaning but badly misguided (and possibly well bribed) politicians just couldn’t agree on the ‘right’ way to combine these features, so they did the worst thing that they could have done — they simply failed to make a decision… (at least they didn’t do what our esteemed New York State politicians have been doing lately)

I ran into this issue about a year ago while working with JSF Managed Beans… I wanted to use a @PostConstruct method to load data for a view page — I needed to access a few repository beans to load the data properly, and I wanted the Managed Bean to act as a transactional boundary… seemed to be an eloquent way to provide for bookmarkable pages in JSF, which is notoriously difficult… Anyway, I was unable to do this directly, as the semantics for @PostConstruct don’t allow it…

Turns out this is problematic with Spring’s usage of @PostConstruct as well… while experimenting with Spring 2.5 a few nights ago, I setup a quick experiment with some JPA Entities and the new annotation-based dependency injection mechanisms (big fan so far, by the way)… I hacked together a test bean that had a method marked with @PostConstruct and @Transactional, which created a single instance of an Entity and persisted it to the database to test that everything was working… but it didn’t work… no errors, just no data in the database…

I’ve seen this symptom before related to mis-configured transactions, so I looked there first — I copied the JPA code into another method, and marked it with “@Transactional (propagation=Propagation.MANDATORY)”, and it gave me an error because there was no existing transactional context… huh? A little research led me to several articles indicating that these two items can’t work together… Oddly enough, if I put the JPA code into another class, everything worked fine…

This is one of those odd restrictions that makes working with Java EE just a little more annoying than it should be… it’s not a huge deal but it does force you to change your programming style in some cases, and it forces you to think about things you shouldn’t have to think about… Spring’s implementation in this regard is somewhat surprising — after all, Spring isn’t a Java EE container… it seems that they could have made their implementation act a little closer to what you would expect, or, if they’re not willing to distort how the standard annotations work, perhaps they aught to create their own version…

I’m just glad the Java EE standards committee hasn’t figured out a way to tax us yet…