Use Spring with GWT dispatch

From the GWT dispatch site:

Inspired by Ray Ryan’s Best Practices For Architecting Your GWT App session at Google I/O 2009, „gwt dispatch“ is an implementation of the ‚command pattern‘ discussed at the beginning of the video.

The project uses Gin in the frontend and Guice in the backend. Guice defines a very nice dependency injection framework, and as such, competes partially with the Springframework. But the Springframework is by far more than dependency injection, and I don’t want to miss any of its features in the backend.

So I took a look at the gwt dispatch sources, and decided to use Spring to setup the server side of the dispatch service. GWT dispatch extensively uses constructor injection. This works perfectly with Spring, but not with plain servlets. So I needed to rewrite the DispatchServiceServlet a little…

Instead of using constructor injection, I use setter injection. This way the servlet can be simply added to the web.xml. The servlet lifecycle initializes servlets before they are service-ready. I use the initialization callback method to autowire the servlet instance.

Here is my web.xml:

I am using annotation based configuration in my project, so the spring configuration file is very concise:

The component scan will add any properly annotated class to the spring application context. Obviously, the classes in the GWT dispatch project are not properly annotated. So I created the classes in my projects that are needed by the DispatchService implementation:

The action handler registry is the place where the ActionHandlers are kept. I used the collection autowire feature to get a list of all handlers registered in the Spring application context.

The last step is to add ActionHandlers to the Spring context. For obvious reasons I prefer to keep my action handlers „Spring free“ – that’s why I created my own annotation to identify action handlers:

I am not sure if I need to setup the retention policy – I should have a look at that…

All I need to do now is to add handlers to any package below the server package. The Spring component scan will automatically find the handlers and add them to the Spring application context and further inject them to the handler registry.

Here is a simple ActionHandler:

I am very happy with this approach as it allows me to add new action (command) handlers without any configuration overhead. Simply dropping the implementation somewhere in the server package will do all the magic.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.