Tuesday, February 15, 2011

Simple Spring bean autowiring in GWT servlet

Update: there is easier way of doing this.
Some time ago i've posted a solution to expose Spring bean as GWT remote service.
That solution supports all Spring stuff like AOP annotations, @Transactional, @Secured from Spring security etc.
But it is no a very easy to remember, it is sometimes tricky to support through IDE and all these features are not always needed, especially when you already have business logic layer that implements all security, transaction demarcation and whatever.
So when you need GWT RemoteService servlet just to delegate all the work to some Spring bean following solution comes handy, mainly because it is only a few lines of code long and very easy to remember.
You need to create a parent class for all your GWT servlets that slightly extends RemoteServiceServlet:
public class SpringGwtServlet extends RemoteServiceServlet {
    public void init(ServletConfig config) throws ServletException {
And then implement your services as usual but extend your class instead of default RemoteServiceServlet defining fields for autowired dependencies and marking them with @Autowired annotation.
public class ReportServiceImpl extends SpringGwtServlet implements ReportService {
    private ReportManager reportManager;
    public Report createReport(long id) {
        return reportManager.createReport(id);
Tested with Spring 2.5.6 and 3.0.x