Monday, June 20, 2011

How to Integrate Spring with GWT Servlet

One thing you may be wondering when you start a new (and maybe your first) GWT project using spring framework on the back-end is how can we autowire the remote service servlets with the Service beans on the backend?

There are many ways to achieve this, but my favorite is very simple and direct, and it may be a great solution if you're looking on how to autowire a servlet too, and is to create a new superclass for all our RemoteServiceServlets, I called that superclass SpringServiceServlet, and it looks like this:
 package com.juancavallotti.server;  

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
*
* @author juancavallotti
*/
public class SpringRemoteServiceServlet extends RemoteServiceServlet {
private static final long serialVersionUID = 1L;

@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
WebApplicationContextUtils
.getRequiredWebApplicationContext(getServletContext())
.getAutowireCapableBeanFactory()
.autowireBean(this);
}

}

So from now on, we just extend this class when writing our services and we get full autowire capabilities.

Hope you find it useful.

No comments:

Post a Comment