@DataSourceDefinition — A Hidden Gem from Java EE 6

In the old days, DataSources were configured — well, they were configured in lots of different ways… That’s because there was no ‘one way’ to do it — in JBoss, you created an XML file that ended in ‘-ds.xml’ and dumped it in the deploy folder… in Glassfish, you either use the admin console or muck with the domain.xml file… in WebLogic you used the web console… and this was all well and good — until I worked with an IT guy who told me just how much of a pain in the ass it was…

Up until then, it wasn’t such a big deal to me — I set it up once, and that was that… then I ran into this guy a few jobs ago who liked to bitch and complain about how much harder it was to deploy our application than the .NET or Ruby apps he was used to… he had to deploy our data source, then he had to deploy our JMS configurations — only then would our application work… in the other platforms, that was all built into the app (I’ll have to take his word for it, since I haven’t actually deployed anything in either platform)… I was a but surprised at first, and then I realized that maybe he had a point… nah, it couldn’t be, he must just be having a bad day (lots of us were having bad days back then 🙂 )…

Then I ran into Grails, which is dead simple — you have a Groovy configuration file that has your db info in it… you even have the ability to specify different ‘environments’, which can change depending on how you create your archives or run your app… pretty slick…

The Gem

Well, lo and behold, we now have something that’s nearly equivalent in Java EE 6 — the @DataSourceDefinition attribute… it’s a new attribute that you can put on a class that provides a standard mechanism to configure a JDBC DataSource into JNDI, and as expected, it can work with local JNDI scopes or the new global scope, meaning you can have an Environment Configuration that uses this attribute making it shareable across your server… it works like this:


import javax.annotation.sql.DataSourceDefinition;
import org.jboss.seam.envconfig.Bind;
import org.jboss.seam.envconfig.EnvironmentBinding;

@DataSourceDefinition (
className="org.apache.derby.jdbc.ClientDataSource",
name="java:global/jdbc/AppDB",
serverName="localhost",
portNumber=1527,
user="user",
password="password",
databaseName="dev-db"
)
public class Config {
...
}

As you would expect, that annotation will create a DataSource that will point to a local Derby db, and stick it into JNDI at the global address ‘java:global/jdbc/AppDB’, which your application, or other applications can refer to as needed… no separate deployment and no custom server-based implementation — this code should be portable across any Java EE 6 server (including the Web Profile!)…

It’s almost perfect!

In typical Java EE style, there’s one thing that just doesn’t appear to be working the way I’d like it — it doesn’t appear to honor JCDI Alternatives (at least not in Glassfish)… Here’s what I’m thinking — we should be able to have a different Config class for each of our different environments… in other words, we’d have a QAConfig that pointed to a different Derby db, a StagingConfig that pointed to a MySQL db somewhere on another server, and a ProductionConfig that pointed to kick ass, clustered MySQL db… we could then use Alternatives to turn on the ones that we want in certain environments with a simple XML change, and not have to muck with code… unfortunately, it doesn’t appear to work — it appears in Glassfish that it is processing them in an undeterministic order, with (presumably) the class that is processed last overwriting the others that came before it…

There is a solution, though, and it is on the lookup side of the equation — using JCDI Alternatives, we can selectively lookup the DataSource that we’re interested in, and then enable that Managed Bean in the beans.xml file… it’s definitely not ideal, since we need to actually inject all of our DataSources into JNDI in all scenarios, but it works, it’s something I can live with, and is probably easily fixed in a later Java EE release… Update: Looks like it’s in the plan, according to this link — thanks, Gavin 🙂

Here’s how it works — first the ‘common’ case, probably for a Development environment:


@RequestScoped
public class DSProvider {
@Resource (lookup="java:global/jdbc/AppDB")
private DataSource normal;

public DataSource getDataSource() {
return normal;
}
}

Simple enough — has a field that looks up ‘jdbc/AppDB’ from JNDI, and provides a getter… now for QA:


@RequestScoped @Alternative
public class QADSProvider extends DSProvider{
@Resource (lookup="java:global/jdbc/AppQADB")
private DataSource normal;

public DataSource getDataSource() {
return normal;
}
}

Pretty much the same, except this does the lookup from ‘jdbc/AppQADB’, and it is annotated with @Alternative… so how do these things work together? Take a look:


@Named
public class Test {
@Inject
private DSProvider dsProvider;

...
}

Again, simple — we’re injecting a DSProvider instance here, and presumably running a few fancy queries… Nothing Dev-ish or QA-ish here at all, which is the beauty of Alternatives… finally, when building the .war file for QA, we turn on our Alternative in the beans.xml, like so:




com.mcorey.alternativedatasource.QADSProvider


You’ll notice that this solution requires us to rebuild our .war file for QA, which I obviously don’t like — not to worry, there will be support for this in the Seam 3 Environment Configuration Module, which will effectively create a binding by mapping from one JNDI key to another… I have no idea what the syntax will look like at this point, but it should be pretty straight forward, and will allow us to — you guessed it — build our .war one, and copy it from place to place without modification…

M

http://pagead2.googlesyndication.com/pagead/show_ads.js

Say hello to the Seam 3 Environment Configuration module

A funny thing happened after my last post — I got an email from Dan Allen, from RedHat, with some interest in making my last JCDI Portable Extension — EnvironmentBindingExtension — into a Seam 3 Module… pretty cool for a fairly modest effort at finding a new way to solve a problem I’ve faced in the past… it will be my first official foray into open source (not counting that one line NetBeans patch I submitted in, like, 2000), so it will be interesting to see how this will actually work from the authoring side, as opposed to the user side, especially in a relatively well organized project like Seam

What it’s about

The idea behind the Environment Configuration module is to inject fairly static configuration information into any JEE 6 environment… it’s typically done outside of your application, in a deployment that isn’t regularly deployed or updated, so you can configure each of your environments separately, including Development, Testing, QA, Staging and Production — once this is done, you can build your application once (or better yet — have a Continuous Integration server build it!), and copy the same binary from server to server without having to reconfigure it, ensuring that the archive that you deploy to production is the same exact archive that you tested in QA… this allows you to streamline your deployment processes, removing any possible human error involved in building your code over, and over, and over again (and in some cases, it’ll save a lot of time if you have a particularly slow build!)

How’s it work? It takes advantage of JNDI — one of the resources that all JEE servers provide… say, for example, that you have a system that needs to access a database, a filesystem, and has a batch process that runs at a specific frequency — in development, you’ll want to point to a personal Derby database, use a local folder on your Windows box for your filesystem, and run the batch process very frequently for testing… QA is similar, although it has different database, but say Staging and Production run on a cluster of Linux boxes that access a MySQL database, use a mounted shared drive for its’ filesystem, and have its’ batch processes run once an hour…

With the Seam 3 Environment Configuration module, you can create a simple .ear file for each of these environments that contains all of this data — create them once, deploy them once, and you’re good to go… take a look at the following example of a configuration that you could use in development:


/**
* An Environment Configuration for Development
* @author Matt
*/
@EnvironmentBinding
@DataSourceDefinition (
className="org.apache.derby.jdbc.ClientDriver",
name="java:global/jdbc/AppDB",
serverName="localhost",
portNumber=1527,
user="user",
password="password",
properties={"create=true"},
databaseName="dev-db"
)
public class Config {
@Bind ("myApp/fs-root")
String rootFolder = "C:\fs-root";

@Bind ("myApp/batch-frequency")
long batchFrequencyInMs = 60 * 1000;
}

Pretty simple — toss this class into its’ own .war file, and it will define three global JNDI entries, one for each of the items mentioned above… your other applications are now free to read these resources in whatever way they need to, even using the standard @Resource(lookup=”java:global/myApp/fs-root”) notation… a similar configuration file would be created for QA, but perhaps the @DataSourceDefinition annotation will use a MySQL datasource, and likewise for Staging and Production…

What next?

Well, there are a few things on my list of features here, including, but not limited to:

  • Test, Test, Test!
  • Using the @Bind attribute on methods, including @Produces methods
  • Support ‘unbinding’, if needed
  • Create a Maven Archetype that could be used to quickly and easily setup an Environment Configuration deployment
  • Create an interface of some kind to be able to review the available findings — either web app or simply JAX-RS based

I am, of course, interested in any ideas or feedback anyone would have, but one goal I would have here is to keep it simple and portable — what this module is intended to do isn’t exactly brain surgery, so I don’t think it’s necessary to throw in too many ‘extras’…

M

http://pagead2.googlesyndication.com/pagead/show_ads.js

External CDI Configuration with Portable Extensions

A common requirement for web and enterprise applications is that they have the capability to configure themselves for each environment without modifying the archive itself — most commonly this is used only for environment specific attributes such as a test vs. production data store, or for Strings describing a file or directory on the file system which will be different on a developers box vs. a clustered production server, or perhaps it is a URL that points to your test payment gateway vs. your production gateway… This is the sort of thing that might easily be done with ‘Alternatives’ in CDI, but many shops put a premium on the ability to package the application once (on a Continuous Integration server, for example) and copy that file from development to integration to QA to staging to production, all of which are on very (very!) different platforms, using different databases, different file systems, and must integrate with different third party environments — configuring this stuff externally means you don’t have to deal with the error prone and possibly time consuming process of building for each environment… unfortunately, this doesn’t appear to be a scenario that Alternatives can help us with…

One resource that works really well for this sort of configuration is JNDI… configure these items on your servers’ JNDI registry independently from your application, and then have your application read the environment configuration settings from here — and CDI makes it very easy to manage both sides of this scenario!

Reading from JNDI

The easier side of this is reading the data from JNDI, so let’s start there… actually, you don’t need CDI at all to start doing this — the easiest way is to use the ‘@Resources’ annotation provided in Java EE 5, like so:


@ApplicationScoped
public class FolderConfig {
@Resource(lookup="java:global/folderToPoll")
private String folderToPoll;

public String folderToPoll() {
return folderToPoll;
}
}

Not much to this — we have an ApplicationScoped Managed Bean which does a lookup from JNDI, and provides a getter for the result… in this case we’re pulling from the new “java:global” context that is provided with Java EE 6 — there’s no reason we couldn’t map this to local context, but frankly, I wanted to fiddle with the global context 🙂

Ok, now on to something more interesting…

Writing to JNDI

Writing to JNDI is pretty easy — get an InitialContext and call ‘bind’… it’s basically an overblown HashMap… for some reason, though, configuring JNDI outside of an application always seems to be more difficult than it should be — several years ago, I actually had to write a JBoss plugin to do it, even though they had quite an advanced configuration mechanism for the time… all I wanted to do was put String ‘A’ at Key ‘B’, but no — not supported out of the box!

That solution was configured by an XML file, which left me dealing with Strings… this solution is better on two accounts: 1) It can bind any Object into JNDI, and 2) it’s a Portable Extension, and should therefore work on any platform… whew!

So here’s how it works — this extension would likely be packaged into a .jar library, and deployed with a simple webapp or ear archive that is packaged separately from the main application… the piece that provides the configuration is actually a class or a set of classes that are annotated to bind certain fields and/or methods into JNDI, like this:


@EnvironmentBinding
public class Env {
@Inject @Bind(jndiAddress="adminUser")
private User admin;

@Bind(jndiAddress="test") private String test = "This is a test";
}

Pretty straight forward — what’s going on here? Well, first you’ll notice that the class is annotated with @EnvironmentBinding — this is a Stereotype annotation that extends @ApplicationScoped, and acts as a marker for the class to be processed later on… further down, we have two fields that are annotated with @Bind and provided with a jndiAddress… this pretty much works as you would expect — the value of that object is injected into JNDI, with the ‘java:global/’ prefix added to the front…

You’ll also notice that one of the elements has its’ value injected into the field — this means that the Objects that are bound into JNDI can be derived from a more complex application if need be, so the support that we have here goes well above and beyond the simple XML file configuration that I dealt with way back when…

So how does this thing work? Well, one implementation that I put together has a two part infrastructure to do the job… remember, the end user should never be exposed to the following two items — the extent of their exposure into this library will be the two annotations shown above…

First, our Portable Extension class:


public class EnvironmentBindingExtension implements Extension {
private Set envBeans = new HashSet();
private BeanManager beanManager;

public void discoverEnvironmentBindingClasses(@Observes ProcessBean pb, BeanManager bm) throws Exception {
this.beanManager = bm;

Bean bean = pb.getBean();
Class beanClass = bean.getBeanClass();

Set sts = bean.getStereotypes();

for (Class st : sts) {
if (st.equals(EnvironmentBinding.class)) {
log.info("Found class annotated with EnvironmentBinding: " + beanClass.getName());

envBeans.add(bean);
}
}
}

public Set getEnvBeans() {
return Collections.unmodifiableSet(envBeans);
}

public BeanManager getBeanManager() {
return beanManager;
}
}

This Extension class is pretty straight forward — as with all Portable Extensions, it starts by implementing the ‘Extension’ interface… in this case, we’re also creating an Observer method for the ‘ProcessBean’ event… this event is fired during the application startup lifecycle for every ‘Bean’ that is discovered in a Bean archive… this will fire for Managed Beans, EJB’s, Interceptors, etc, but here, we’re specifically looking for beans that have the EnvironmentBinding Stereotype on them — that is the trigger to further process this class… in this case, our process simply consists of adding the Bean to our ‘envBeans’ Set for later use… in addition, we provide accessor methods for the BeanManager (which is injected into our Observer method), and the envBeans Set… Now let’s have a look at what we do with these Beans…

The next class is the one that does most of the heavy lifting — it is a Singleton EJB which is marked as a Startup bean, meaning it will be instantiated upon application startup, after the CDI discovery phases are complete… in this case, we have created a PostConstruct method to do our work for us:


@Singleton
@Startup
@ApplicationScoped
public class BindingsProcessor {
@Inject
private EnvironmentBindingExtension bindingExtension;

@PostConstruct
public void processBindings() throws Exception {
Set envBeans = bindingExtension.getEnvBeans();

log.info("Processing EnvironmentBinding Classes: "+envBeans);

Context appContext = bindingExtension.getBeanManager().getContext(ApplicationScoped.class);
for(Bean bean:envBeans) {
Class beanClass = bean.getBeanClass();

Object beanInstance = appContext.get(bean, bindingExtension.getBeanManager().createCreationalContext(bean));

Field[] fields = beanClass.getDeclaredFields();
for(Field field:fields) {
if(field.isAnnotationPresent(Bind.class)) {
field.setAccessible(true);

String jndi = field.getAnnotation(Bind.class).jndiAddress();
Object val = field.get(beanInstance);

bindValue(jndi, val);
}
}
}
}

Hey, wait a minute — this is pretty simple, too! Iterate over the set of Beans that we’ve collected, use reflection to find all of the fields that are annotated with @Bind, and bind the value into the appropriate JNDI location… I’ve even removed the JNDI api work here, because it’s not interesting at all…

This could be expanded in a couple of way, most obviously to allow methods to act as Binders as well… I do want to discuss my choice here of using the Singleton EJB as well, since I’ve had a few posts recently which talk about doing away with EJB’s altogether — well, initially I was attempting to use the ‘AfterBeanDiscovery’ or ‘AfterDeploymentValidation’ events to trigger this loading, but I was having trouble getting an instance of ‘Env’ that was capable of having its’ injection points… er… injected…

The Singleton EJB is somewhat of a last-ditch sanity effort, but after considering it for a few days, I’m actually alright with it… the Startup Singleton EJB’s are something that has interested me for a while, and it proves its’ usefulness here, but what’s more, I’m still able to take the EJB interface out of the end-user’s experience here… they simply need to make use of the EnvironmentBinding annotation, and be on their merry way, as long as they are deployed in a container which supports Singletons (which all Java EE 6 containers do)… that being said, I’m hoping that Gavin will show me what the heck I was doing wrong 🙂

One other thing — using an @Inject method on an ApplicationScoped bean doesn’t appear to do the trick… reading the spec, it appears to be caused by the fact that ApplicationScoped beans are ‘active’ during Servlet calls, EJB calls, etc — meaning it doesn’t have it’s own ‘startup’ lifecycle, but depends on the lifecycle of other Java EE component models… interesting, to be sure — adding a more generic Startup capability would be a cinch if done similar to how I’ve done this…

Wow, that was a lot of words

So what does this all mean? Basically, it just shows another way of skinning that old, damn cat that is environment configuration — but it also shows that it’s pretty darn easy to put together some CDI extensions, and when working with the surrounding Java EE specs and resources, that it can be done in a minimal amount of code… in this case, I was looking at a requirement that I often have to support external configuration — one that CDI doesn’t accommodate out of the box… with a few lines of code, it turned out to be possible to break that box open and stuff some more toys inside 🙂

Finally, the more complete code samples can be found here — the EnvironmentBinding project has the core code, the TestEnvironmentConfig project shows a test web application that could be used to create the binding configuration, and the EnvTest project is an application which makes use of the JNDI entries… have fun!

M

http://pagead2.googlesyndication.com/pagead/show_ads.js

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

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

Woo hoo!

Can you smell that smell? That’s the smell of a nice, smooth, clean sheet of ice down at your local rink… that’s right, it’s hockey season, baby, the best time of the year, and the Rangers are looking to make a run for the Cup (they also apparently sold out the entire season in less than an hour… as the great John Buccigross would say, “Holy Shnikies!”)… My fantasy draft is tonight, and things start up next week, which means I’ll have a reason to watch TV again (that is, if Time Warner still carries Versus — I haven’t checked since June… the NHL desperately needs to get back onto ESPN!)

I hope to take my son to several games of our local minor league team this year — he’s old enough now to at least sit through most of the game, and perhaps to learn some of the subtleties of the crosscheck and the one-timer (I’m holding out next year for the left wing lock)… well, he seems to think it’s cool when someone gets checked into the glass, any way 🙂

So even if you hate hockey, sports, or whatever, at least go down to the rink to take in that smell… I swear, there’s nothing like the smell of the ice!

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