More Fun with DWR and Spring

Recently, I posted some experiences using DWR. Yesterday, Peter and I were trying to connect our DWR/Ajax component to Spring, so that I could inject my dependencies in some elegant way.

My first instinct was to create a simple utility that could use annotations to determine what needs to be injected. It’d work something like this. I’d have some component, like a DAO, that I’d want to inject in my DWR service:

public class MyAjaxService {
  private ThingDAO thingDAO;

  public ThingDAO getThingDAO() {
    return this.thingDAO;
  public void setThingDAO(ThingDAO thingDAO) {
    this.thingDAO = thingDAO;

I’d create an InjectBeanannotation, and some utility to perform bean introspection on the service, and find all properties with the required annotation.

The only part that required some extra thought was how I could access the Spring WebApplicationContext from inside my DWR component.

Turns out, there’s a magic, ThreadLocal utility called “WebContextFactory” that’s a standard part of the DWR environment. So I could do this:

WebContext context = WebContextFactory.get();
ServletContext servletContext = context.getServletContext();

Once I had the servlet context, I could use a standard Spring utility to grab the WebApplicationContext:

WebApplicationContext springContext =

I created my DependencyInjector utility, and it all worked like magic.

Unfortunately, after that, I RTFMed the DWR documentation, and discovered a much simpler approach.

In my DWR “configuration” file, dwr.xml, I could set up a service like so:

<create creator="spring" javascript="MyAjaxService">
  <param name="beanName" value="MyAjaxService"/>

The creator="spring" part tells DWR to go off to the Spring WebApplicationContext file and lookup a bean using the specified beanName. Oh well; that was a bit of a waste of time, but I learned me some stuff.

It's only fair to share...
Share on Facebook
Tweet about this on Twitter
Share on LinkedIn

Leave a Reply