views:

38

answers:

1

We have a legacy web application (not Spring based) and are looking for best practices to autowire some newer Spring configured (thread safe) service beans into instance variables in several of the legacy servlets. Rewriting every servlet to Spring MVC is out of scope. For testability, we do not want any Spring specific bean lookup code in the Servlets to look up beans by name or similar.

Note that we are not concerned about web specific bean scopes such as session or request; all services are singleton scope.

Below shows relevant code snippet

MyServlet extends LegacyServletSuperclass
{
   private MyThreadSafeServiceBean wantThisToBeAutowiredBySpring;
   ....

}
+2  A: 

You can use @Configurable in combination with a <context:load-time-weaver />, and use @Autowired in your servlets. This allows for classes that are not instantiated by spring to use be handled by spring.

You may use another approach as well - in the init(..) method of your servlet:

ApplicationContext ctx = 
    WebApplicationContextUtils.getWebApplicationContext(servletContext);
if (ctx != null) {
    ctx.getAutowireCapableBeanFactory().autowireBean(this);
}

This will set all spring dependencies (where @Autowired/@Resource are used). It will work in case the service classes are defined in spring, which I assume is the case.

From testability point of view - if there isn't a web application context, nothing will happen, and you can manually set your dependencies.You can also mock the application context, if needed, depending on how are you testing your servlets.

Bozho
Thanks, we'll look into those. I'll accept the answer if no other ideas come in and implement successfully
Pete