There is a much more sophisticated way to do that. There is SpringBeanAutowiringSupport
inside org.springframework.web.context.support
that allows you building something like this:
public class MyServlet extends HttpServlet {
@Autowired
private MyService myService;
public void init(ServletConfig config) {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
}
This will cause Spring to lookup the ApplicationContext
tied to that ServletContext
(e.g. created via ContextLoaderListener
) and inject the Spring beans available in that ApplicationContext
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…