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;
....
}
You can use
@Configurablein combination with a<context:load-time-weaver />, and use@Autowiredin 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:This will set all spring dependencies (where
@Autowired/@Resourceare 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.