Question

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;
   ....

}
Was it helpful?

Solution

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 you are testing your servlets.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top