从JBoss中的servlet访问Spring bean

我想在JBoss中编写一个简单的servlet,它将在Spring bean上调用一个方法。 目的是允许用户通过点击URL来启动内部作业。

在servlet中获取对Spring bean的引用的最简单方法是什么?

JBoss Web服务允许您使用@Resource注释将WebServiceContext注入服务类。 有没有类似的可用于普通的servlet? 解决这一特殊问题的网络服务将使用大锤来破碎坚果。

您的servlet可以使用WebApplicationContextUtils来获取应用程序上下文,但是您的servlet代码将直接依赖于Spring Framework。

另一个解决方案是配置应用程序上下文以将Spring bean作为属性导出到servlet上下文:

       

您的servlet可以使用从servlet上下文中检索bean

 SpringifiedJobbie jobbie = (SpringifiedJobbie) getServletContext().getAttribute("jobbie"); 

有一种更复杂的方法可以做到这一点。 在org.springframework.web.context.support中有SpringBeanAutowiringSupport ,它允许你构建这样的东西:

 public class MyServlet extends HttpServlet { @Autowired private MyService myService; public void init(ServletConfig config) { super.init(config); SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); } } 

这将导致Spring查找与该ServletContext绑定的ApplicationContext (例如,通过ContextLoaderListener创建)并注入该ApplicationContext可用的Spring bean。

我找到了一种方法:

 WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); SpringifiedJobbie jobbie = (SpringifiedJobbie)context.getBean("springifiedJobbie");