从JBoss中的servlet访问Spring bean

时间:2009-01-21 22:11:12

标签: java spring java-ee servlets jboss

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

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

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

3 个答案:

答案 0 :(得分:60)

有一种更复杂的方法可以做到这一点。 SpringBeanAutowiringSupportorg.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的{​​{1}}(例如通过ServletContext创建)并注入ContextLoaderListener中可用的Spring bean。

答案 1 :(得分:31)

您的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");

答案 2 :(得分:8)

我找到了一种方法:

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