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 {
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        WebApplicationContextUtils.
                getRequiredWebApplicationContext(getServletContext()).
                getAutowireCapableBeanFactory().
                autowireBean(this);
    }
}
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 {
    @Autowired
    private ReportManager reportManager;
    
    public Report createReport(long id) {
        return reportManager.createReport(id);
    }
}
Tested with Spring 2.5.6 and 3.0.x

5 comments:

  1. Thank you Max for posting this - it worked the first time. While I have experience with Spring, I'm new to GWT and I wasn't sure how to integrate the two.

    ReplyDelete
  2. Hi George.
    Actually this is very simple solution, but it is limited at the same time. For example you will not be able to correctly process exceptions thrown in servlet class.
    Personally I prefer aspectJ based method described here http://blog.maxmatveev.com/2011/05/spring-beans-and-annotations-in-servlet.html with exception processing like here http://blog.maxmatveev.com/2011/06/gwt-and-spring-security-integration-as.html

    ReplyDelete
  3. Веллкам. Но с аспектами http://blog.maxmatveev.com/2011/05/spring-beans-and-annotations-in-servlet.html решение все-таки красивее. И проще.

    ReplyDelete
  4. Thanks a lot Max ....it was really helpful for me

    ReplyDelete