从 JBoss 中的 servlet 访问 Spring bean

2022-09-01 17:54:47

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

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

JBoss Web 服务允许您使用@Resource注释将 WebServiceContext 注入到您的服务类中。有没有类似的东西可以在普通的servlet中工作?解决此特定问题的Web服务将使用大锤来压碎螺母。


答案 1

有一种更复杂的方法可以做到这一点。里面有一个允许你构建这样的东西: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查找与之相关的(例如通过创建),并注入该中可用的Spring豆。ApplicationContextServletContextContextLoaderListenerApplicationContext


答案 2

你的 servlet 可以使用 WebApplicationContextUtils 来获取应用程序上下文,但随后你的 servlet 代码将直接依赖于 Spring 框架。

另一种解决方案是配置应用程序上下文,以将 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");

推荐