繁体   English   中英

从JBoss中的servlet访问Spring bean

[英]Access Spring beans from a servlet in JBoss

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

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

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

有一种更复杂的方法可以做到这一点。 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。

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

我找到了一种方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM