您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

从JBoss中的servlet访问Spring bean

从JBoss中的servlet访问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");

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

Jave 2022/1/1 18:18:40 有364人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶