你的servlet可以使用WebApplicationContextUtils来获取应用程序上下文,但是你的servlet代码将直接依赖于Spring Framework。
另一个解决方案是配置应用程序上下文,以将Spring bean作为属性导出到servlet上下文:
<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
<property name="attributes">
<map>
<entry key="jobbie" value-ref="springifiedJobbie"/>
</map>
</property>
</bean>
你的servlet可以使用以下方法从servlet上下文中检索Bean:
SpringifiedJobbie jobbie = (SpringifiedJobbie) getServletContext().getAttribute("jobbie");
有更复杂的方法可以做到这一点。有SpringBeanAutowiringSupport
里面org.springframework.web.context.support
可以让你建立这样的事情:
public class MyServlet extends HttpServlet {
@Autowired
private MyService myService;
public void init(ServletConfig config) {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
}
这将导致Spring查找与其ApplicationContext
绑定的对象ServletContext
(例如通过创建ContextLoaderListener
),并注入其中可用的Spring bean ApplicationContext
。